JavaScript的MVVM库Vue.js入门学习笔记

2020-06-16 06:33:21易采站长站整理

}
}
}
});

其他实例:


Vue.component('modal', {
template: '#modal-template',
props: {
show: {
type: Boolean,
required: true,
twoWay: true
}
}
});

6.注册


// 定义
var MyComponent = Vue.extend({
template: '<div>A custom component!</div>'
});

// 注册
Vue.component('my-component', MyComponent);

// 创建根实例
new Vue({
el: '#example'
});
<div id="example">
<my-component></my-component>
</div>

或者直接写成:


Vue.component('my-component', {
template: '<div>A custom component!</div>'
});

// 创建根实例
new Vue({
el: '#example'
});
<div id="example">
<my-component></my-component>
</div>

7.使用prop 传递数据
实例一:


Vue.component('child', {
// 声明 props
props: ['msg'],
// prop 可以用在模板内
// 可以用 `this.msg` 设置
template: '<span>{{ msg }}</span>'
});
<child msg="hello!"></child>

实例二:


Vue.component('child', {
// camelCase in JavaScript
props: ['myMessage'],
template: '<span>{{ myMessage }}</span>'
});
<!-- kebab-case in HTML -->
<child my-message="hello!"></child>

8.动态props


<div>
<input v-model="parentMsg">
<br>
<child v-bind:my-message="parentMsg"></child>
</div>

使用 v-bind 的缩写语法通常更简单:


<child :my-message="parentMsg"></child>

9.Prop 绑定类型
prop 默认是单向绑定:当父组件的属性变化时,将传导给子组件,但是反过来不会。这是为了防止子组件无意修改了父组件的状态——这会让应用的数据流难以理解。不过,也可以使用 .sync 或 .once 绑定修饰符显式地强制双向或单次绑定:

比较语法:


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

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

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

其他实例:


<modal :show.sync="showModal">