菜鸟Vue学习笔记(四)
上周学习了使用Vue来操作表单元素进行数据双向绑定,今天我们来学习下Vue中的组件,Vue中的组件作用就是去封装一些常用的页面标签,将其当做一个整体,以便在其他位置直接使用一组标签。例如:
<script>
Vue.component("hello", {
template: "<div><input type='text'/><span>hello</span></div>"
});
</script>
这是定义了一个全局的组件,在其他位置使用方式为:
<div id="box">
<hello></hello>
</div>
好,我们初步的认识了组件,感觉它就像一个自定义标签一样。那么Vue的组件到底有哪些方式定义呢?Vue组件分为全局组件和局部组件,顾名思义,全局组件就是在所有引用到此组件的地方都可以使用,而局部组件只能在定义局部组件对应的地方使用。
例如:定义全局组件
<script>
Vue.component("hello", {
template: "<div><input type='text'/><span>hello</span></div>"
});
</script>
定义局部组件:
<script>
var v = new Vue({
el: "#box",
components: {
"test" : {
template: "<div><input type='text'/><span>hello</span></div>"
}
}
});
</script>
组件不一定都是单纯的静态组件,也可以在组件中绑定变量。例如:
<script>
Vue.component("hello", {
template: "<div><input type='text' v-bind:value='a'/><span>{{msg}}</span></div>",
props: ["msg"]
});
var v = new Vue({
el: "#box",
data: {
a: "0"
}
});
</script>
使用时,需要指定变量,例如:
<div id="box">
<hello v-bind:msg="a"></hello>
</div>
基本的组件使用我们暂时说到这,下次我们说说路由的使用。