首先,我在main.js里vue的原型上挂载了一个全局变量
...
vue.prototype.$global="全局变量"
...
然后在vue的template模板里面调用,是能够正常显示的
...
<span>{{this.$global}}</span>
...
但是我在使用了作用域插槽的组件里调却返回了null,去掉this.之后是能够正常显示的
//child
<div class="child">
<slot :user="user">{{user.name}}</slot>
</div>
//parent
...
<child>
<template v-slot:default="scope">{{scope.user.gender}} {{this.$global}}</template>
</child>
...
所以有点小疑问,作用域插槽是不是改变了this的指向,如果改变了,改变之后的this指的是哪里
作用域插槽在经过
vue-template-compiler
转换后,会变成render
函数的第2个参数(data
对象)中的scopedSlots
对象的一部分。scopedSlots
对象的key
是插槽名,值是render
函数。这个
render
函数在后续的createElement
过程中,会被normalizeScopedSlot
标准化处理。而
normalizeScopedSlot
中会将这个函数包装,改变其上下文。