从一张白纸开始学习前端,掐指一算也大概一年了
但对于$Props
的应用,一直无法深入理解
可能碍于本身逻辑能力较差的关係,再加上网路的文章教程都是以下这种写法
<script type="text/x-template" id="my-component"> <div class="component"> <div> ParentMsg: {{ parentMsg }} </div> <div> ChildMsg: {{ msg }} </div> </div> </script> <script> Vue.component('my-component', { props: ["parentMsg"], template: '#my-component', data: function () { return { msg: 'Msg of Child!' } } }); new Vue({ el: '#app', data: { msg: 'Msg of Parent!' } }); </script>
因此一直无法去区分这种模式若改成VueCli的话该怎么去撰写
才决定纪录一篇简单的使用笔记,方便日后理解
$Props
首先我在components中新增了一个person.vue
文件,并将样板设为按钮,并注册name:
<template> <div> <button>{{ name }}</button> </div></template><script>export default { props: ['name']}</script>
在上面的程式码中,我们在 props
里注册了一个 name
的值。我们可以在模板内使用已注册的 prop。
现在就可以透过在html tag中加入 name 属性从 family.vue
将 name 属性的值传入 props
:
<template> <div id="app" class="container"> <h1 style="font-size:2rem">我的家人有:</h1> <ul> <li>奶奶</li> <li>爸爸</li> <li>妈妈</li> <li>姊姊</li> <li>弟弟</li> </ul> <Person name="按钮1"></Person> <Person name="按钮2"></Person> </div></template><script>import Person from '@/components/person.vue'export default { data () { return { value: '' } }, components: { Person },
画面中所显示的样子
接着在注册第二个props
组件名称
<template> <div> <button @click="handleclick">{{ name }}</button> </div></template><script>export default { props: ['name', 'handleclick']}</script>
再到family.vue
将handleclick
绑定,简单写两个function方便做为输出观察
<template> <div id="app" class="container"> <h1 style="font-size:2rem">我的家人有:</h1> <ul> <li>奶奶</li> <li>爸爸</li> <li>妈妈</li> <li>姊姊</li> <li>弟弟</li> </ul> <Person name="按钮1" :handleclick = 'click1'></Person> <Person name="按钮2" :handleclick = 'click2'></Person> </div> {{ valueStatus }}</template><script>import Person from '@/components/person.vue'export default { data () { return { valueStatus: '' } }, components: { Person }, methods: { click1 () { this.valueStatus = '我爱爸爸!!' }, click2 () { this.valueStatus = '我爱妈妈!!' } }}</script>
测试输出结果: