开发技巧-Vue

111 阅读1分钟

开发技巧-Vue

v-bind="props"vbind="props"、v-bind="attrs"、v-on="listeners"

父组件 - parent.vue

多个子组件引用的时候按照 这个方法引入即可

v-bind="$props": 可以将父组件的所有props下发给它的子组件,子组件需要在其props:{} 中定义要接受的props。

this.$props: 当前组件接收到的 props 对象

v-bind="$attrs": 将调用组件时的组件标签上绑定的非props的特性(class和style除外)向下传递。在子组件中应当添加inheritAttrs: false(避免父作用域的不被认作props的特性绑定应用在子组件的根元素上)。当前例子就是 parent.vue 上的展示了 index.vue 传过来的 test="123"

this.$attrs :包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class 和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。

v-on="将父组件标签上的自定义事件向下传递其子组件可以直接通过emit(eventName)的方式调用。 vm.$listeners: 包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。

<template>
    <div>
        <h3>父组件</h3>
        <div>组件名上绑定的非props特性($attrs): {{ $attrs }}</div>
        <app-child test="456" v-on="$listeners" v-bind="$props"></app-child>
    </div>
</template>

<script>
import AppChild from "./child.vue";
export default {
    data() {
        return {};
    },
    inheritAttrs: false,
    props: ["name", "age"],
    components: {
        AppChild,
    },
    mounted() {
        this.$emit("start1");
        console.log(this.$props);		// { age: '18', name: '传给父组件的值' }	父子组件的打印都一直
        console.log(this.$attrs);		// {test: '456'}
        console.log(this.$listeners);	// {start1: ƒ, start2: ƒ}	父子组件的打印都一直
    },
};
</script>

子组件 - child.vue

<template>
    <div>
        <h3>子组件</h3>
        <div>父组件传递过来的名称: {{ name }}</div>
        <div>父组件传递过来的年龄: {{ age }}</div>
    </div>
</template>

<script>
export default {
    data() {
        return {};
    },
    props: ["name", "age"],
    mounted() {
        this.$emit("start2");
        console.log(this.$props);		// { age: '18', name: '传给父组件的值', }	父子组件的打印都一直
        console.log(this.$attrs);		// {test: '123'}
        console.log(this.$listeners);	// {start1: ƒ, start2: ƒ}	父子组件的打印都一直
    },
};
</script>

引用父组件 - index.vue

    <template>
      <div>
        <h1>props、属性、事件传递</h1>
        <app-parent test="123" :name="name" :age="age" v-on:start1="say1" @start2="say2"></app-parent>
      </div>
    </template>
 
    <script>
      import AppParent from './parent.vue';
      export default {
        data() {
          return {
              age: '18',
              name: '传给父组件的值',
          };
        },
        components: {
            AppParent
        },
        methods: {
            say1() {
                console.log('第一个。。。。。');	// 后打印这个 
            },
            say2() {
                console.log('第二个。。。。。');	// 先打印这个 
            }
        }
      }
    </script>

[参考]blog.csdn.net/xueyue616/a…