我们一般通过new Vue({})的方式得到一个Vue实例
当我们注册Vue组件的时候,使用的是Vue.component(tagName,options)
全局注册
//JS部分 首先全局注册一个组件
Vue.component("hello",{"template:<div>hello</div>"})
//然后得到Vue的实例
var hello=new Vue({
el:"#hello")
})
//HTML部分
<div id="hello">
<hello></hello>
</div>
局部注册
<div id="hello"><hello></hello></div>
//JS
var part={text:"<div>hello world</div>"};
var hello=new Vue({
el:"#hello",
components:{"hello":part}
//或者是components:("hello",part)
})
DOM模板解析注意事项
当我们使用<ul>、<ol>、<table>、<select>等元素的时候,我们会受到HTML的限制,某些元素只能出现在特定的包含中,例如option元素,这时候自定义组件就会被视为无效组件,我们通常解决这类问题的方法就是给他添加一个is特性
<table>
<tr is="my-row"></tr>
</table>
关于data
构造 Vue 实例时传入的各种选项大多数都可以在组件里使用。只有一个例外:data 必须是函数。
当我们传入的时候 请将data写为函数的形式,但是要注意,所有的组件都会获得这个data的引用就比如:
var data = { counter: 0 }
Vue.component('simple-counter', {
template: '<button v-on:click="counter += 1">{{ counter }}</button>',
data: function () {
return data
}
})
///我们会发现我们按一个按钮,另一个按钮的值也会改变,所以我们要返回一个全新的对象
var temp=new Vue({
el:"#temps",
components:{
"temp": {
template:"<button @click='couter()'>{{count}}</button>",
data:function(){
return {
count:0
}
},
methods:{
couter:function(){
return this.count=this.count+1;
}
}
}
}
});
组件组合
在Vue中最常见的关系就是父子关系,在A组件中使用了B组件,这个时候,父组件使用prop向下传递,子组件通过事件向上传递
<div id="prop">
//使用kebab-case
<prop my-message="hello"></prop>
</div>
//JS
var prop=new Vue({
el:"#prop",
components:{
"prop":{
//注意,当这里使用驼峰式命名法的时候对应的在你的HTML特性中要使用短横线分隔式命名
props:["myMessage"],
template:"<div>{{myMessage}}</div>"
}
}
})
当然 我们也可以是使用v-bind指令和v-model指令将用户输入的值绑定到prop上
<div id="prop">
<input v-model="hello"></input>
<br>
<prop :my-message="hello"></prop>
</div>
//JS
var prop=new Vue({
el:"#prop",
data:{
hello:" "
},
components:{
"prop":{
props:["myMessage"],
template:"<div>{{myMessage}}</div>",
}
}
});
*当我们传递数值的时候,切记加入v-bind,否则我们传入的是一个string类型的字符串,而不是一个数字
单向数据流
当我们在使用prop的时候,我们要注意了,当父组件的数据变化的时候,会传导给子组件,但是子组件并不会将数据传导给父组件,这是为了防止父组件的数据被修改。当我们在使用prop的时候
- 会将父组件的数据当做局部数据来处理
- 会将prop作为原始数据传入,最后由子组件处理其他数据
//第一种
定义一个局部变量,用prop初始化他
props:["message"],
data:function(){
return {
myMessage:this.message
}
}
//第二种问题的解决方法,定义一个计算属性
props:["message"],
computed:{
setMessag:function(){
return this.message.toString();
}
}
本文介绍了Vue.js中组件的全局及局部注册方式,并演示了如何使用props进行数据传递以及如何处理DOM模板解析时遇到的问题。此外,还讲解了data属性的正确使用方法以及组件间的单向数据流原则。

被折叠的 条评论
为什么被折叠?



