学了一段时间Vue,现在将Vue中有关的概念整理一下。
组件分为全局组件和局部组件。
全局组件,所有的Vue的实例都可以去使用
//全局组件,所有的实例都可以使用 Vue.component('my-component',{ template:'<div><input type="date"><p>今天天气很好</p></div>' } ); new Vue({ el:'#example' });
<div id="example"> <my-component></my-component> </div>
全局组件可以在任何实例中去引用
上面的例子中注册了一个全局组件,通过Vue.component()注册
局部组件,只能在该组件注册的Vue实例中引用
var Child = { template: '<div>A custom component!</div>' } //局部组件,只能在注册的实例中使用 new Vue({ el:'#app', components:{ Child } });
<div id="app"> <Child></Child> </div>
上面注册了一个局部组件,如上面的代码所示,Child就只能在id为app的div中使用。
子组件,在某个组件中注册的组件,子组件只能在父组件中的模版中使用。
var Child = { template: '<div>Child</div>' } var Parent = { template:'<div>Acustom component <Child></Child></div>', components:{ Child } } Vue.component('parent',Parent); new Vue({ el:'#example' });
上面的代码中Child在Parent中注册,也只能在Parent的模版中使用。
上面的代码也可以用template替换
<div id="app"> <parent></parent> </div> <template id="tmp"> <div>template</div> </template> <script> var Parent = { 'template':'#tmp' } Vue.component('parent',Parent); new Vue({ el:'#app' }); </script>
上面用template模版
例子都比较简单,主要是理解组件的有关概念