在父组件中用render调用子组件,这段代码会输出什么?如下:
点击h5的click事件后:
每次点击click都会触发render函数,因为click中每次都修改data属性title:
父组件:
<script>
// <template>
// <div class="main">
// 由于使用的是vue的运行时js库,js中<br />
// render函数使用后,js中的template属性失效<br />
// html标签模板使用后,render函数失效<br />
// <slot name="s1"></slot>
// <slot name="s2"></slot>
// </div>
// </template>
import test1_1 from './test1-1'
export default {
name: '',
data: function () {
return {
title: '页面one'
}
},
template:
'<div class="main">js中的template <slot name="s1"></slot><slot name="s2"></slot></div>', //此处优先级低于render(),不被执行
render: c => {
console.log('子组件的render')
return c(test1_1)
// return c('h4', {}, 'one:render函数') // 如果子组件与父组件都执行了render(),结果以最后的子级(root > 父级 > 子级的执行顺序)的render为准。这是因为,子组件的render最后执行。
}
}
</script>
<style lang="scss" scoped>
.main {
border: 1px solid green;
padding: 10px 5px;
margin-top: 10px;
line-height: 30px;
}
</style>
子组件test1-1.vue:
<script>
// <template>
// <div>
// test1-1+{{ title }}
// <button @click="change">点我改变title</button>
// </div>
// </template>
export default {
name: '',
data: function () {
return { title: ':test1-1' }
},
created() {
console.log('小子组件created')
},
mounted() {
console.log('小子组件mounted')
},
methods: {
change(e) {
console.log('methods')
this.title = '尝试调用render'
}
},
render: function (c) {
// this.title = 'xiao'
const self = this
console.log('test1-1:render')
return c(
'h5',
{
style: { color: 'green' },
on: {
click: function (e) {
self.title = 'change' + Math.random()
console.log('click')
}
}
},
'test1-1+' + this.title
)
}
}
</script>
</script>
小记录:
// 1,在初始化vue根实例时,要么使用el,要么使用$mount,后者可以延迟挂载
// 2,既有el也有template时,template的优先级高于el(前提是使用的vue库是全的,如果只是runtime库,会报错的,缺少编译功能!!!
// 3,render执行优先级大于template。
// 4,如果在.vue文件中,即vue组件中,没有el,(只讨论)render>template。
// 5,
<template>
高于
render() 高于 template
// 6,如果修改了
<template>
中的属性值(data的属性值被改变),不会触发我们写的render函数。 //
7,如果没有
<template>
,一开始执行的render函数,当修改了data的属性值时,会再次触发render函数的。 与6有区别哦!
版权声明:本文为yudianvictor原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。