小知识,大挑战!本文正在参与「程序员必备小知识」创作活动
本文已参与 「掘力星计划」 ,赢取创作大礼包,挑战创作激励金。
丸子之前写了一篇 vue3前端青铜到黄金王者 - 第16个入门创建可重用组件 ,自定义了的一个可以重用的组件,使用import的方式引入组件。
自定义组件与父组件值传递
先做一个简单组件
进入components 目录复制Wanzi.vue文件为WanziV2.vue
现在代码改为:
<template>
<div class="wanzi">
<h1>{{ name}}</h1>
<h2>
丸子做的Vue组件V2
</h2>
</div>
</template>
<script>
export default {
name: 'WanziV2',
props: {
name: String
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.wanzi {
list-style-type: none;
padding: 0;
}
</style>
WanZiV2 组件
相比前篇博文,这个V2组件的props为name,之前为msg。
下面直接在App.vue 中导入使用:
<template>
<img alt="Vue logo" src="./assets/logo.png"/>
<WanziV2 name="丸子酱的demo"/>
<WanziComp msg="丸子的第一个可重用组件" />
<HelloWorld msg="欢迎参与开发第一个Vue.js App"/>
</template>
\
<script>
import HelloWorld from './components/HelloWorld.vue'
import WanziComp from './components/Wanzi.vue'
//import WanziV2 from "/components/WanziV2.vue"
import WanziV2 from './components/WanziV2.vue'
export default {
name: 'App',
data(){
},
components: {
HelloWorld,
WanziComp,
WanziV2
}
}
</script>
\
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
区别是引入了
运行yarn serve 查看效果:
添加like属性到子组件并绑定父组件的一个变量(ref响应式对象)
子组件WanziV2代码变更如下:
<template>
<div class="wanzi">
<h1>{{ name}}</h1>
<h2>
丸子做的Vue组件V2, 点赞人数:{{like}}
</h2>
</div>
\
</template>
\
<script>
export default {
name: 'WanziV2',
props: {
name: String,
like: Number,
}
}
</script>
\
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
// 没有变更,这里省略
</style>
父组件变更为:
template>
<img alt="Vue logo" src="./assets/logo.png"/>
<button @click="onClick">点赞/收藏/三连!!!</button>
<WanziV2 name="丸子酱的demo" :like="likeNum" />
<WanziComp msg="丸子的第一个可重用组件" />
<HelloWorld msg="欢迎参与开发第一个Vue.js App"/>
</template>
\
<script>
import HelloWorld from './components/HelloWorld.vue'
import WanziComp from './components/Wanzi.vue'
//import WanziV2 from "/components/WanziV2.vue"
import WanziV2 from './components/WanziV2.vue'
\
import { ref } from 'vue'
let likeNum = ref(2)
export default {
name: 'App',
data(){
},
components: {
HelloWorld,
WanziComp,
WanziV2
},
setup(){
function onClick() {
likeNum.value++
console.log('like is ' , likeNum.value)
}
return {
likeNum,
onClick
}
}
}
</script>
\
<style>
// 没有变更,这里省略
</style>
在父亲组件中,丸子酱添加了一个‘点赞/收藏/三连’按钮,点击一次,对likeNum对象值加一。
然后把likeNum引用赋值给了WanziV2组件。这样就达到了父子组件的通信了。
运行yarn serve 查看效果:
总结
本文从一个简单组件入手改造,添加父组件。
可以看出,这种父子值交互,是通过ref对象来衔接的。
是不是很简单?你也试试看,记得点赞收藏支持!
今天就写到这里。
我是丸子,每天学会一个小知识。
一个前端开发
希望多多支持鼓励,感谢