在项目中报了这么一个错误,然后我在博客上面看了一些文章,发现写的都是关于 v-for 的,所以我自己写了一份关于 v-slot 报这个错误的案例,供大家参考
先说一下解决思路,解决思路就是 把要改变的数据放在父组件中改变,而不是子组件中就行,下面来看一下案例代码
错误代码:
容器组件 one.vue
<script setup lang="ts">
import two from "./two.vue"
import three from "./three.vue"
</script>
<template>
<div>
<h1>这是容器组件</h1>
<two>
<template v-slot:header="{data,data1,data2}">
<three :data="data" v-model:data1="data1" v-model:data2="data2"></three>
</template>
</two>
</div>
</template>
<style lang="less" scoped>
</style>
插槽父组件 two.vue
<script setup lang="ts">
import { ref } from 'vue'
const data = ref('123')
const data1 = ref('456')
const data2 = ref('789')
</script>
<template>
<div>
<h2>这是有位置的组件</h2>
<slot name="header" :data="data" :data1="data1" :data2="data2"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
<style lang="less" scoped>
</style>
插槽子组件 three.vue
<script setup lang="ts">
// @ts-ignore
const props = defineProps({
data: String,
})
const data1 = defineModel('data1')
const data2 = defineModel('data2')
const changData = ()=>{
data1.value = 'data1'
data2.value = 'data2'
}
</script>
<template>
<div>
<h3>这是要插入位置的组件</h3>
<el-button @click="changData">点我改变数据</el-button>
<div>{{ data }}</div>
<div>{{ data1 }}</div>
<div>{{ data2 }}</div>
</div>
</template>
<style lang="less" scoped>
</style>
当是这样的时候,就会报上面的错误,下面来看改正之后的代码
正确代码:
容器组件 one.vue
<script setup lang="ts">
import two from "./two.vue"
import three from "./three.vue"
</script>
<template>
<div>
<h1>这是容器组件</h1>
<two>
<template v-slot:header="{data,data1,data2,fun}">
<three :data="data" :data1="data1" :data2="data2" :fun="fun"></three>
</template>
</two>
</div>
</template>
<style lang="less" scoped>
</style>
插槽父组件 two.vue
<script setup lang="ts">
import { ref } from 'vue'
const data = ref('123')
const data1 = ref('456')
const data2 = ref('789')
const fun = ()=>{
data1.value = 'data1'
data2.value = 'data2'
}
</script>
<template>
<div>
<h2>这是有位置的组件</h2>
<slot name="header" :data="data" :data1="data1" :data2="data2" :fun="fun"></slot>
<slot></slot>
<slot name="footer"></slot>
</div>
</template>
<style lang="less" scoped>
</style>
插槽子组件 three.vue
<script setup lang="ts">
// @ts-ignore
const props = defineProps({
data: String,
data1: String,
data2: String,
fun: {type:Function,default:()=>{}}
})
// const data1 = defineModel('data1')
// const data2 = defineModel('data2')
const changData = ()=>{
// data1.value = 'data1'
// data2.value = 'data2'
props.fun()
}
</script>
<template>
<div>
<h3>这是要插入位置的组件</h3>
<el-button @click="changData">点我改变数据</el-button>
<div>{{ data }}</div>
<div>{{ data1 }}</div>
<div>{{ data2 }}</div>
</div>
</template>
<style lang="less" scoped>
</style>
这样就可以解决那个报错问题了