Vue组件
1.0 基本使用
父组件可以向子组件传值,子组件也可以调用父组件的函数;但子组件不能修改父组件的值;详见:https://cn.vuejs.org/v2/guide/components-props.html
<head>
<title>test</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
<!-- 此元素是vue实例的挂载点,此元素的所有内容称之为模板,模板也可以在创建vue实例时书写 -->
<div id="root">
<input v-model="inputValue">
<button @click="handleSubmit">提交</button>
<ul>
<!-- <li v-for='(item,index) of list' :key="index">
{{item}}
</li> -->
<todo-item v-for="(item,index) of list" :kye="index" :t-content="item" :index="index" @delete = "handleDelete"></todo-item>
<!--
通过声明属性给子组件传递参数
注:HTML中的特性名是大小写不敏感的,所以浏览器会把所有大写字符解释为小写字符。这意味着当你使用DOM中的模板时,驼峰命名法的prop 名需要使用其等价的 kebab-case (短横线分隔命名) 命名;
@delete = "handleDelete" 是指监听todo-item这个实例的delete事件。一旦delete事件被触发,将调用handleDelete方法,
因为handleDelete方法是在父实例的模板中,因此会调用父实例的handleDelete方法。
-->
</ul>
</div>
<script type="text/javascript">
// 定义全局组件,组件名称为todo_item
Vue.component("todo-item",{
props:['tContent','index'], // 接收外部传入的参数tContent
template:'<li @click="handleClick">{{tContent}}</li>', // 使用外部传入的参数tContent
methods:{
handleClick:function(){
// 触发一个事件,事件名为delete,并传入参数this.index
this.$emit("delete",this.index);
}
}
});
// 组件就是一个vue实例
// 注册局部组件
// var todoTtem = {
// template:'<li>item</li>'
// }
// 创建vue实例
new Vue({
el:"#root",
// components:{ // 声明在当前实例中要使用的局部组件
// "todo-item":todoTtem // 在当前实例中,通过标签名todo-item来使用组件todoTtem
// },
// template:'<h1>{{testMsg1}}</h1>', // 此处也可以为挂载点设置模板
data:{
inputValue:"",
list:[]
},
methods:{
handleSubmit:function(){
this.list.push(this.inputValue);
this.inputValue = "";
},
handleDelete:function(index){
this.list.splice(index,1);
}
}
});
</script>
</body>
2.0 可以在子组件上绑定v-model和原生事件,详见:
https://cn.vuejs.org/v2/guide/components-custom-events.html