Vue Component Usage Basis

  vue.js

This blog post is used to record.vueHow to use the component.

You can put the component code according totemplatestylescriptTo the corresponding.vueIn the file.

Template (template), initial data (data), accepted external parameters (props), methods (methods), life cycle hook function (lifecycle hooks)。

Basic steps

InhtmlComponents Used in

<div id="app">
    <my-component></my-component>
</div>

To use a component, you first need to create a constructor:

var myComponent = Vue.extend({
    template: `<p>myComponent</p>`
})

To use this constructor as a component, you need to useVue.component(tag, constructor)Registration:

Global registration

// 全局注册组件,tag 为 my-component
Vue.component('my-component', myComponent)

Vue.component('my-component', MyComponent)This isGlobal registrationThe first parameter isName of the registered componentThe second parameter isComponent constructor;

The of the option objecttemplateProperty is used to define what the component will renderHTML;

Local registration

new Vue({
    el: '#app',
    components: {
        'my-component': myComponent
    }
})

Child components can only be found in the parent component’stemplateTo be used in.

Component option issues

When defining options for a component,dataAndelOption must use function.

IfdataOption points to an object, which means that all component instances share onedata.

So you should use a function asdataOption to let this function return a new object:

Vue.component('my-component', {
    data: function () {
        return {a: 1}
    }
});

Similarly,elOptions forVue.extend()The middle time must also be a function.

Data transfer

There are three ways to transfer data between Vue.js components:

  1. props
  2. Component communication
  3. slot

props

propsIs a field of component data that is expected to be passed down from the parent component. Because ..The scope of the component instance is isolatedTherefore, the subassembly needs to explicitly use thepropsOption to get the data of the parent component.

propsThe options can beLiteral quantityExpressionBinding modifier.

Literal quantity

<div id="app">
    <child msg="hello!"></child>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    Vue.component('child', {
        props: ['msg'],
        // prop 可以用在模板内
        // 可以用 this.msg 设置
        template: `<span>{{msg}} Are you tired?</span>`
    });

    new Vue({
        el: "#app"
    })
</script>

HTMLFeatures are not case sensitive. The name form iscamelCaseThepropWhen used as a feature, you need to convert tokebab-case(separated by dashes):

<div id="app">
    <child my-message="hello!"></child>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    Vue.component('child', {
        props: ['myMessage'],
        template: `<span>{{myMessage}} Are you tired?</span>`
    });

    new Vue({
        el: "#app"
    })
</script>

Dynamic

Usev-bindBinding dynamicspropsData to parent component. Every time the data of the parent component changes, it is also transmitted to the child component.

<div id="app">
    <input v-model="parentMsg"><br>
    <child :my-message="parentMsg"></child>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
    Vue.component('child', {
        props: ['myMessage'],
        template: `<span>{{myMessage}} Are you tired?</span>`
    });

    new Vue({
        el: "#app",
        data: {
            parentMsg: 'hello!'
        }
    })
</script>

Binding type

You can use binding modifiers:

.sync, two-way binding
.once, single binding

<!-- 默认为单向绑定 -->
<child :msg="parentMsg"></child>

<!-- 双向绑定 -->
<child :msg.sync="parentMsg"></child>

<!-- 单次绑定 -->
<child :msg.once="parentMsg"></child>

propThe default is one-way binding: when the attribute of the parent component changes, it will be conducted to the child component, but not vice versa.

However, it should be noted that ifpropIs an object or array passed by reference. Modifying it within a child component affects the state of the parent component, regardless of the binding type used.

Prop type validation

Vue.component('example', {
    props: {
        propA: Number,// 基础类型检测 (`null` 任何类型)
        propM: [String, Number],// 多种类型 (1.0.21+)
        propB: {// 必需且是字符串
            type: String,
            required: true
        },
        propC: {// 数字,有默认值
            type: Number,
            default: 100
        },
        propD: {// 对象|数组的默认值应当由一个函数返回
            type: Object,
            default: function () {
                return {msg: 'hello'}
            }
        },
        propE: {
            // 指定这个 prop 为双向绑定
            // 如果绑定类型不对将抛出一条警告
            twoWay: true
        },
        propF: {// 自定义验证函数
            validator: function (value) {
                return value > 10
            }
        },
        propG: {
            // 转换函数(1.0.12 新增)
            // 在设置值之前转换值
            coerce: function (val) {
                return val + '';// 将值转换为字符串
            }
        },
        propH: {
            coerce: function (val) {
                return JSON.parse(val);// 将 JSON 字符串转换为对象
            }
        }
    }
});