1.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<!--父在 app 中拿到数据发送给儿子 -->
<lcoal v-bind:title="msg"></lcoal>
<lcoal1 v-bind:items="lession"></lcoal1>
</div>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
//局部组件
const lcoal = {
template: "<h1>{{title}}</h1>",
//拿到父传递过来的数据 名字必须相同 放到组件中进行渲染
props: ['title']
};
const lcoal1= {
template: "<ul><li v-for='item in items'>{{item}}</li></ul>",
//拿到父传递过来的数据 名字必须相同 放到组件中进行渲染
//props: ['items']
props:{
items:{
//传递的数据必须是数组类型的
type:Array,
//如果没有传递数据过来默认使用的数据
default:['java']
}
}
};
const app = new Vue({
el: "#app",
data: {
msg: "大家好!",
lession:['java','php','python']
},
components: {
lcoal,
lcoal1
}
})
</script>
</body>
</html>
2.单机子的增加方法,不能直接修改父属性里面的值,需要父自己修改属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<h2>num: {{num}}</h2>
<counter v-bind:count="num":inc="increment" v-on:dec="decrement"></counter>
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
Vue.component("counter", {
template:`
<div>
<button @click="plus">加</button>
<button @click="reduce">减</button>
</div>`,
props:['count'],
methods:{
plus(){
this.$emit("inc");
},
reduce(){
this.$emit("dec");
}
}
})
var app = new Vue({
el:"#app",
data:{
num:0
},
methods:{ // 父组件中定义操作num的方法
increment(){
this.num++;
},
decrement(){
this.num--;
}
}
})
</script>
</body>
</html>