VUE cheat list

9月 14, 2022 |

覆盖知识点

  • v-bind(:) 数据模型值绑定到元素
  • v-on(@) 事件处理器
  • v-model v-bind+v-on 用于form中输入控件和数据模型同步
  • and v-slot(#) 插槽
  • custom component
  • custom directives
  • custom event
  • Route

index.js 定义路由

import Playground from '../views/Playground.vue'
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [{
          path: '/playground',
          name: 'playground',
          component: Playground
	}]
})

App.vue 路由连接

<RouterLink to="/playground">playground</RouterLink>

Playground

<script>
    import ComponentA from "./ComponentA.vue"
    export  default {
        //定义要使用的组件
        components:{ ComponentA},
        //声明数据模型,data() 返回对象,而不是直接定义对象
        data(){
            return {
                items :[{id:1, name :"hello vue.js"}],
                xSize: 1
            }
        },
        methods: {
            enlargeText(n){
                this.xSize = Number(this.xSize) + Number(n);
            }
        }
    }
</script>

<template>
    <form method="post" action="#">
        <!--v-bind equivalent to v-bind + v-on数据模型和控件任一方值变动都同步到另一方-->
        <input name="xSize" v-model="xSize"/>
        <button type="submit">submit</button>
    </form>
    <div :style="{fontSize: xSize + 'em'}">
        <!--v-bind 等于:name, :id 一次将所有属性传入-->
        <!--@enlarge-text 调用自定义函数-->
        <ComponentA v-for="item in items"  v-bind="item"   @enlarge-text="enlargeText">
            <!--#slotA 是v-slot:slotA的shorthand,接收slot 绑定的值-->
            <template #slotA="slotProps">
                <!--插入接收的值-->
                <span>{{slotProps.msg}}</span>
            </template>
        </ComponentA>
    </div>
</template>

ComponentA.vue

<template>
    <div>
        <!--自定义指令-->
        <h4 v-highlight="'yellow'">{{name}}</h4>
        <!--emit 自定义事件-->
        <button @click="$emit('enlarge-text',0.1)">enlarge text</button><br/>
        <!--命名插槽,:msg 传值-->
        <slot name="slotA" :msg="msg">slot</slot>
    </div>
</template>

<script>
    export  default {
        //声明组件暴露的属性
        props: {
            name:String ,
            id:Number
        },
        //声明组件触发事件
        emits:[
            'enlarge-text'
        ],
        data(){
            return {
                msg:"javacoder.cn"
            }
        },
        directives:{
            //自定义指令v-highlight, 组件挂载到父节点时触发
            highlight: {
                //vue2 和vue3区别: bind → beforeMount |inserted → mounted
                mounted(el, binding, vnode, prevVnode) {
                    el.style.background = binding.value
                }
            }
        }
    }
</script>

Posted in: WEB开发

Comments are closed.