父->子传值
- 在子组件上 配置props属性 属性中写上自定义属性名
{
props:['自定义属性名']
}
- 在父组件中找到子组件的组件标签,在组件标签上边使用v-bind:自定义属性名="父组件要发送的数据"
<子组件标签 v-bind:自定义属性名="要发送的数据"></子组件标签>
- 在子组件需要使用数据的地方 直接将第一步中 自定义属性名当做data来使用(插值语法直接使用)
{
template:`
<div>{{自定义属性名}}</div>
`
}
实例:评论功能实现(头像随机生成)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="./css/public.css">
<link rel="stylesheet" href="./font/iconfont.css">
<link rel="stylesheet" href="./css/index.css">
</head>
<body>
<div id="app">
<div class="container">
<headers></headers>
<comment></comment>
</div>
</div>
<script src="./js/vue.min.js"></script>
<script>
Vue.component('headers', {
template:`
<div class="title">
评论
</div>
`
})
Vue.component('comment', {
data() {
return {
val:'',
txt:[],
pho:['./img/1.awebp','./img/2.awebp','./img/3.awebp','./img/4.awebp','./img/5.awebp','./img/6.awebp','./img/7.awebp','./img/8.awebp'],
newpho:[],
}
},
template:`
<div class="comment">
<input type="text" placeholder="请输入评论内容" v-model.trim="val">
<button @click="publick">发送</button>
<lists :msg="txt" :pho="newpho"></lists>
</div>
`,
methods: {
publick(){
if(this.val.length){
this.txt.push(this.val)
this.newpho.push(this.pho[Number(Math.floor(Math.random()*8))])
this.val=''
}
else{
alert('请输入内容,OK?')
}
}
},
})
Vue.component('lists', {
props:['msg','pho'],
template:`
<ul class="lists" v-if="msg.length>0">
<li v-for="(item,index) in msg " :key="index">
<div class="meleft">
<img :src="pho[index]" alt="">
<div class="content">
<span>{{item}}</span>
</div>
</div>
<good></good>
</li>
</ul>
<div v-else class="empty">暂无评论内容</div>
`
})
Vue.component('good', {
data() {
return {
num:false,
}
},
template:`
<div class="good" @click="show">
<span :class="['iconfont','icon-dianzan', {active:num}]"></span>
</div>
`,
methods: {
show(){
this.num=!this.num
}
},
})
new Vue({
el:'#app'
})
</script>
</body>
</html>