......
<script>
/*
子组件想要修改父组件传递过来的参数时,方式有两种
1.重新定义一个变量来接收父组件传递过来的参数
2.通知父组件进行修改,
1>可以使用this.$emit方式 向外触发事件,触发事件时是驼峰式命名
父组件中可以对该事件进行监听,@为监听事件符号,在标签上监听时不能使用驼峰式命名,而使用横线间隔语法命名
子组件向父组件触发一些事件时,emits:['add'],//意义在于通过emits会知道向外究竟触发什么事件,维护性更高,不局限于写一个数组,也可以使用对象
2>也可使用类似于双向绑定的方式实现
父组件中通过v-model方式向子组件传递数据,子组件接收时需满足条件:
a.子组件中接收的参数必须名为modelValue(默认名)
b.点击向外触发事件时,事件名字为update:modelValue,固定,触发的值会替换掉父组件中原来的值
c.如果想将modelValue改成别的名字,可以通过v-model:+名字形式
组件间双向绑定高级内容
子组件触发点击事件时,事件名可以使用handle...形式,比较规范,语义化更好
*/
const app = Vue.createApp({
template: `
<test :count='count' @add-one='handleAddOne'/>
<test2 v-model='count2' v-model:count3='count3'/>
/* captalize */
<test3 v-model.uppercase='str'/>
`,
data() {
return {
count: 1,
count2: 2,
count3: 3,
str:'abc'
}
},
methods: {
handleAddOne(params) {
// this.count += params
this.count = params
}
}
})
// 全局组件-测试
app.component('test', {
props:['count'],
// emits:['addOne'],//意义在于通过emits会知道向外究竟触发什么事件,维护性更高,不局限于写一个数组,也可以使用对象
emits:{
addOne:(count)=>{
//会接受到向外传递的参数的值
if(count>0){
return true
}
return false
}
},
data(){
return{
tempCount:this.count
}
},
methods:{
handleClick(){
// this.tempCount+=1
//固定写法,向外部触发addOne事件,且可以进行参数传递,传参时也可以直接进行计算
// this.$emit('addOne',5)
this.$emit('addOne',this.count+5)
}
},
template: `
<div>
<div @click='handleClick'>
<div>tempCount:{{tempCount}}</div>
<div>count:{{count}}</div>
</div>
</div>
`
})
app.component('test2',{
props:['modelValue','count3'],
template:`
<div @click='handleClick'>测试2------{{modelValue}}+'~~~~~~~~~'{{count3}}</div>
`,
methods:{
handleClick(){
this.$emit('update:modelValue',this.modelValue+5)
this.$emit('update:count3',this.count3+10)
}
},
created(){
console.log('modleValue',this.modelValue)
}
})
app.component('test3',{
props:{
'modelValue':String,
/* 传递过来的修饰符,默认修饰符是一个空对象 */
'modelModifiers':{
default:()=>{
}
}
},
methods:{
handleClick(){
let newValue = this.modelValue + 'b'
if(this.modelModifiers.uppercase){
newValue = newValue.toUpperCase()
}
this.$emit('update:modelValue',newValue)
}
},
template:`
<div @click='handleClick'>测试1213---{{modelValue}}</div>
`
})
/* 注意:使用组件时需要先注册完组件再将该vue实例挂载到root元素上 */
/* vm代表的就是vue应用的根组件
vm获取根节点上数据,调用data时,data前加一个$,操作vm时,数据改变,视图也会自动发生改变
如果该数据是根数据,也可以直接vm. 调用
*/
const vm = app.mount('#root')
//app.unmount()//让vue失效
</script>
......