我正在迁移到Vue SFC,在使用计算(computed)属性时遇到问题.

使用以下代码,我希望创建两行,并且可以通过单击顶行(标题行)来切换底行(内容行)的可见性.

<!-- components/Note.vue -->
<script setup>
import { marked } from "marked";
import { ref, computed } from "vue";

const props = defineProps({
  id: Number,
  title: String,
  create: String,
  content: String
});

const showContent = ref(false);
const elContent = ref(null);

const scrollHeight = computed(() => {
  return elContent.value.scrollHeight + "px";
});

const markedContent = computed(() => {
  return marked.parse(content.value);
})
</script>

<template>
  <div class="row" @click="showContent=!showContent">
    <div class="col-9">{{ title }}</div>
    <div class="col-3">{{ create }}</div>
  </div>
  <div class="row" :style="{height:showContent?scrollHeight:0}" ref="elContent">
    <div class="col">{{ markedContent }}</div>
  </div>
</template>

以下是错误消息

[Vue warn]: Unhandled error during execution of render function (9)
"
"
" at <Note"
"id=27"
"title=\"1Lorem Ipsum\""
" ..."
">"
"
"
" at <App>"

[Vue warn]: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/core (9)
"
"
" at <Note"
"id=27"
"title=\"1Lorem Ipsum\""
" ..."
">"
"
"
" at <App>"

Unhandled Promise Rejection: ReferenceError: Can't find variable: content

但是,如果我不使用Computed属性,而是直接在模板中使用marked.parse方法,那么一切都会顺利进行.

<!-- This is fine -->
<div class="row" :style="{height:showContent?scrollHeight:0}" ref="elContent">
  <div class="col">{{ marked.parse(content) }}</div>
</div>

我希望有人能告诉我为什么会发生这种情况,以及我应该如何在脚本设置中使用计算(computed)属性.

推荐答案

使用props.probName模式访问脚本设置文件中的props .但是,在模板部分中,您必须直接使用probName.

因此,在您的情况下,使用props.content而不是content来解决问题.

const markedContent = computed(() => {
  return marked.parse(props.content);
//return marked.parse(props.content.value);
})

props名称来自props 的定义,您可以在其中 Select 一个变量名称来保存所有属性.

// Here you've defined a variable name (props) that represents all properties
const props = defineProps({
  id: Number,
  title: String,
  create: String,
  content: String
});

在设置中直接访问props

如果您希望直接访问props (如模板中所示),您可以在以下位置销毁props:

const {content, id, title, create} = defineProps({
  id: Number,
  title: String,
  create: String,
  content: String
});

const markedContent = computed(() => {
  return marked.parse(content);
})

Vue.js相关问答推荐

VueJS使所有组件崩溃,而不是只有一个

Pinia+Vue 3状态react 性-StoreToRef的替代方案

vuetify/mdi 不显示图标

是否可以将 nuxt3 与类星体框架一起使用

如何在 VUE.js 中重新刷新时保持多层 b-collapse 菜单打开?

在 vue.js 中添加新类时样式不适用

vue js导航到带有问号的url

Vue:将点击事件绑定到动态插入的内容

如何在 vue 路由中导航到 Bootstrap-vue 选项卡中的特定选项卡?

用 axios 搜索:新字符时取消之前的请求

Vue-router:循环路由以动态创建

如何在 vue.js 模板中显示空间而不是 undefined 和 null?

Vue 3 如何获取有关 $children 的信息

为什么 vue 文档说 refs 不是响应式的,而实际上它们是响应式的

Select 下拉列表中的复选框后如何清除 v-autocomplete(多个)搜索输入?

基于媒体查询的vue绑定值

带有后退按钮的 Vue.js 路由

VueJS 路由 - 使用子路由和 Vuetify 时如何停止多个活动路由(active routes)?

如何在 Vue.js 中延迟 @keyup 处理程序

IOS在输入焦点上显示键盘