Those things about vue (3)

Offer arrives, dig friends to pick up! I am participating in the 2022 Spring Recruitment Check-in Event, click to view the details of the event

1. Talk about how they communicate

The communication method of vue2:

  • Slightly (I will add it later when I have time. If you need it, you can look at the vue documentation first)

The communication method of vue3:

  • props
  • emit
  • provide/inject
  • attrs
  • v-model
  • vuex
  • mitt
  • ref

props and emits

// 父组件内容
<dialogChild :dataValue="title"></dialogChild>

setup(){
  const state = reactive({
    title:'你好哟'
  })
  return{
    ...toRefs(state)
  }
}

// 子组件内容
props:{
  dataValue:{
    type:String,
    default:()=>''
  }
}

<div>child-first:{{dataValue}}</div>
复制代码

emit

// 子组件内容
<el-button size="small" type="primary" @click="changData">点击</el-button>

export default {
  name: "test",
  emits: ['changData'],
  props: {
    dataValue: {
      type: String,
      default: () => ''
    }
  },
  setup(props, {emit}) {
    const number = ref('1')
    const state = reactive({
      text: '测试',
      count: '2'
    })
    const changData = () => {
      emit('changData', state.text)
    }
    return {
      ...toRefs(state),
      number,
      changData
    }
  }
}

// 父组件内容
<dialogChild :dataValue="title" @changData="getTextData"></dialogChild>

const getTextData = (value) => {
  console.log(value) // 测试
}
复制代码

Note: One thing to note here is that some have a warning

[Vue warn]: Extraneous non-emits event listeners (changData) were passed to component but could not be automatically inherited because component renders fragment or text root nodes. If the listener is intended to be a component custom event listener only, declare it using the "emits" option.

Solution: declare the custom event name under
emits: ['changData']

These two, provide/inject
, can cross all boundaries, but they are not responsive, so they are generally used in components.

// 父组件内容
setup() {
  const state = reactive({
    title: '你好哟',
    name: '超越'
  })
  const getTextData = (value) => {
    console.log(value)
  }
  provide('name', state.name)  // 注入
  return {
    ...toRefs(state),
    getTextData
  }
}

// 子组件或者孙组件获取内容
setup() {
  const getName = inject('name') // 获取
  console.log('getName:', getName) // 超越
}
复制代码

2. Afterword

At present, only a few are listed here, and I will add them later. If it is helpful to you, please follow your heart ❤️

Remarks: Please indicate the source when reprinting. The final interpretation right belongs to the author.

Guess you like

Origin juejin.im/post/7078867873766064165