[ Vue3-组件传参-监控 ]


Vue3组件使用, watch监控组件参数

1. 父组件

  • 传给子组件的数据类型为ref
  • 而且前面要写v-model:才是<父组件>-<子组件>数据双向传递

xxx.vue

<template>
    <notebookmain v-model:editor_content="editor_content_ref" v-model:editor_title="editor_title_ref"></notebookmain>
</template>

<script>
// 导入组件
import notebookmain from '../components/NotebookMain.vue'
export default {
    // 调用组件
    components: {
        notebookmain
    },
    setup() {
        ...
        const editor_content = ref('')
        const editor_title = ref('')
        return {
            ...
            editor_content,
            editor_title
        }
    }
}
</script>

2. 子组件

  • watch监控父组件的ref类型, 为下面的写法

xxx.vue

<script>
export default {
  // 1. 定义改<子组件> 接受的参数
  props: {
    editor_content: {
      Type: String,
      default: ''
    },
    editor_title:{
      Type: String,
      default: ''
    },
  },
  emits: ["update:editor_content"],   // 语法糖update: xxxx传递参数给父组
  // 2. 在setup中<接受父组件> 传的参数, emit为子组件给父组件传递参数
  setup(props, {emit}) {
      ...
      // 3. 实例化<文章对象>
    const editor = ref(new Editor({
      extensions: [
        Underline,
        Document,
        Paragraph,
        Text,
        Italic,
        Strike,
        Heading,
        CodeBlockLowlight
          .extend({
            addNodeView() {
              return VueNodeViewRenderer(CodeBlockComponent)
            },
          })
          .configure({ lowlight }),
        Link.configure({
          openOnClick: false,
        }),
      ],
      content: props.editor_content ? props.editor_content : content,
      // 4. 当此<子组件>编辑内容改变时触发
      onUpdate: () => {
        // 给父组件传参绑定
        // emit('传递给父组件的变量名', '传递给父组件的内容')
        emit("update:editor_content", editor.getHTML())
      }
    })
    )

      // 监控
      watch([() => props.editor_content,() => props.editor_title],
          (newValue, oldValue) => {
            // 6. 重新设置渲染<文章的内容>
            editor.value.commands.setContent(newValue[0], false) // 内容
            xxxxx.value = newValue[1]  // 标题
          },
    )
      return{
          ...
      }
  }
}
</script>