Vant 4官网例子使用与setup语法糖冲突解决方法

Barrage 弹幕 - Vant 4

例子:弹幕组件的使用

html 复制代码
export default {
  setup() {
    const defaultList = [
      { id: 100, text: '轻量' },
      { id: 101, text: '可定制的' },
      { id: 102, text: '移动端' },
      { id: 103, text: 'Vue' },
      { id: 104, text: '组件库' },
      { id: 105, text: 'VantUI' },
      { id: 106, text: '666' },
    ];

    const list = ref([...defaultList]);
    const add = () => {
      list.value.push({ id: Math.random(), text: 'Barrage' });
    };

    return { list, add };
  },
};

官网的数据处理部分使用export暴露函数写的这与 setup语法糖有冲突。

html 复制代码
<script setup>
</script>

解决方案:

去除外层暴露函数及返回。

html 复制代码
//原数据格式,官网提供。
export default {
  setup() {
    const defaultList = [
      { id: 100, text: '轻量' },
      { id: 101, text: '可定制的' },
      { id: 102, text: '移动端' },
      { id: 103, text: 'Vue' },
      { id: 104, text: '组件库' },
      { id: 105, text: 'VantUI' },
      { id: 106, text: '666' },
    ];

    const list = ref([...defaultList]);
    const add = () => {
      list.value.push({ id: Math.random(), text: 'Barrage' });
    };

    return { list, add };
  },

//处理后的,删除可以使用setup语法糖。
const defaultList = [
      { id: 100, text: '轻量' },
      { id: 101, text: '可定制的' },
      { id: 102, text: '移动端' },
      { id: 103, text: 'Vue' },
      { id: 104, text: '组件库' },
      { id: 105, text: 'VantUI' },
      { id: 106, text: '666' },
    ];

    const list = ref([...defaultList]);
    const add = () => {
      list.value.push({ id: Math.random(), text: 'Barrage' });
    };

去除外层

export default {

setup() {

return { list, add }; }, };

然后引用组件就可以愉快的玩耍了

html 复制代码
<script setup>
const defaultList = [
      { id: 100, text: '轻量' },
      { id: 101, text: '可定制的' },
      { id: 102, text: '移动端' },
      { id: 103, text: 'Vue' },
      { id: 104, text: '组件库' },
      { id: 105, text: 'VantUI' },
      { id: 106, text: '666' },
    ];

    const list = ref([...defaultList]);
    const add = () => {
      list.value.push({ id: Math.random(), text: 'Barrage' });
    };
</script>
<template>
    <van-barrage v-model="list" ref="barrage" :auto-play="false">
  <div class="video" style="width: 100%; height: 150px"></div>
</van-barrage>
<van-space style="margin-top: 10px">
  <van-button @click="add" type="primary" size="small" :disabled="!isPlay">
    弹幕
  </van-button>
  <van-button @click="toggle()" size="small">
    {{ isPlay ? '暂停' : '开始' }}
  </van-button>
</van-space>
</template>

这个是轮播图的处理例子,其他带数据的组件都可以这样处理。

冲突的原因是setup语法糖已经帮我们对数据进行暴露处理了。

相关推荐
开开心心就好27 分钟前
免费PDF处理软件,支持多种操作
运维·服务器·前端·spring boot·智能手机·pdf·电脑
全宝1 小时前
🎨前端实现文字渐变的三种方式
前端·javascript·css
yanlele1 小时前
前端面试第 75 期 - 2025.07.06 更新前端面试问题总结(12道题)
前端·javascript·面试
妮妮喔妮1 小时前
【无标题】
开发语言·前端·javascript
fie88891 小时前
浅谈几种js设计模式
开发语言·javascript·设计模式
谦行1 小时前
深度神经网络训练过程与常见概念
前端
Simon_He2 小时前
一个免费的在线压缩网站超越了付费的压缩软件
前端·开源·图片资源
巴巴_羊3 小时前
React Ref使用
前端·javascript·react.js
拾光拾趣录3 小时前
CSS常见问题深度解析与解决方案(第三波)
前端·css
徊忆羽菲3 小时前
Echarts3D柱状图-圆柱体-文字在柱体上垂直显示的实现方法
javascript·ecmascript·echarts