vue3 Example Code for Comparison of Different Syntax Formats

  • 2021-11-10 08:45:13
  • OfStack

The default template mode is similar to vue2, and setup function is used in components


//  Parent component 
<template>
  <div>
    <div>
      <div>{{city}}</div>
      <button @click="changeReactive"> Change reactive</button>
      <button @click="handleFather"> Click the parent component </button>
    </div>
    <Child ref="childRef" @handleBtn="handleBtn" @testClick="testClick" city=" Chengdu " />
  </div>
</template>

<script>
import { ref, onMounted, toRefs, reactive } from 'vue'
import Child from './Child.vue'

export default {
  components: {
    Child
  },
  setup () {
    const handleBtn = (val) => {
      console.log('btn', val)
    }

    const testClick = (val) => {
      console.log('testClick', val)
    }

    const childRef = ref(null)

    const handleFather = () => {
      childRef.value.observed.a = 666 // The parent component modifies the value of the child component 
      console.log(' Methods for getting child components ', childRef.value)
      //  Subcomponents need to be defined expose If you don't define it, you need to return the corresponding function, 1 If you don't use it on the page, you will not return it directly 
      // Direct through expose Just expose the method or value you need 
    }

    //  Pass setup Write the method of the function, need to return, the method used on the page, and the value 
    //  If it is reactve The value defined by the definition, the value rendered on the page by deconstruction is not responsive , Need to pass toRefs Transform, and then deconstruct 
    // ...toRefs(testReactive)
    
    const testReactive = reactive({
      city: ' Beijing ',
      age: 22
    })

    const changeReactive = () => {
      testReactive.city = ' Chongqing '
    }

    return {
      handleBtn,
      testClick,
      handleFather,
      ...toRefs(testReactive),
      changeReactive,
      childRef
    }
  }
}
</script>


// Subcomponent 
<template>
  <div>
    {{observed.a}}
    <button @click="handleBtn"> Click </button>
  </div>
</template>

<script>
import { defineProps, defineEmits, defineEmit, defineExpose, reactive } from 'vue'

export default {
  props: {
    city: String
  },

  /*  This is mainly set up to make ctx.attrs This property cannot be accessed  */
  /* props Some attributes are set on the attrs On, it will not be displayed  */

  emits: ['testClick'],  // The purpose of setting this is to make attrs There is no corresponding custom method on, 
  // Subcomponent if set peops , then in attrs You can't access the corresponding value on 
  //arrts In vue3 With custom methods mounted, and class , style
  // In vue2 The custom method in is mounted to the ,$listeners , in vue3 Medium $liseners Has been removed 

  setup (props, ctx) {
    const { expose, emit } = ctx
    const handleBtn = () => {
      console.log('btn', ctx)
      emit('testClick', 666)
    }

    const observed = reactive({
      a: 1
    })

    function clickChild (value) {
      observed.a = value
    }

    expose({
      clickChild, // Exposes a custom method, and the parent component calls 
      observed//  Expose the values of subcomponents 
    })

    return {
      observed,
      handleBtn
    }
  }
}
</script>

Write setup on script tag < script setup >


//  Parent component 
<template>
  <div>
    <button @click="handleFather"> Click on the parent </button>
    <Child ref="childRef" @handleBtn="handleBtn" @testClick="testClick" city=" Chengdu " />
  </div>
</template>

<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
//  You don't have to write in this way return Export the methods and values used on the page. What do you need to use directly in the vue Deconstruct the corresponding defin
const childRef = ref(null)

const handleBtn = (val) => {
  console.log('btn', val)
}

const testClick = (val) => {
  console.log('testClick', val)
}

const handleFather = () => {
  console.log(' Methods for getting child components ', childRef.value)
  childRef.value.testFatherClick()  // The parent component calls the method of the child component 
  //  Subcomponents pass through defineExpose Expose the corresponding method 
}

</script>


//  Subcomponent 
<template>
  <div>
    <button @click="handleBtn"> Click </button>
  </div>
</template>

<script setup>
import { defineProps, defineEmits, defineExpose, reactive } from 'vue'

const props = defineProps({
  city: String
})

const emit = defineEmits(['handleBtn', 'testClick'])

const handleBtn = () => {
  // console.log('btn', props, emit)
  emit('testClick', 12)
}

const testFatherClick = () => {
  console.log(' Test the parent component and click on the child component ')
}

const observed = reactive({
  a: 1
})

defineExpose({ // Expose the method to the parent group price 
  testFatherClick,
  observed
})

</script>

<style scoped>
</style>

Render through jsx, very close to react, which is also my most recommended way. jsx also supports ts, and. vue file does not support tsx well


//  Parent component 
import { ref, reactive } from 'vue'
import Child from './Child.jsx'

const Father = {
  setup() {
    //  In jsx Object defined in the ref To use on a page, you need to pass the .value To visit 
    const city = ref(' Beijing ')

    const changeCity = () => {
      city.value = ' Hangzhou '
    }

    const childRef = ref(null)

    const handelFather = (add) => {
      // Also by exposing in the component expose Method 
      // city.value = ' Hangzhou '
      console.log('childRef', childRef.value)
    }

    const testChildClick = (val) => {
      console.log(' Test subcomponent click ', val)
    }

    return () => {
      return (
        <div>
          <div>{city.value}</div>
          <button onClick={changeCity}> Change the city </button>
          <button onClick={handelFather}> Click on the parent </button>
          <Child testChildClick={testChildClick} ref={childRef} />
        </div>
      )
    }
  }
}

export default Father


// Subcomponent 
import { ref, reactive } from 'vue'

const Child = {
  props: {
    testChildClick: Function
  },

  setup(props, { emit, expose }) {
    const { testChildClick } = props
    const testFatherClick = () => {
      console.log(' Test the parent component and click on the child component ')
    }

    const handelBtn = () => {
      // emit('testChildClick') // In jsx This way won't work 
      // console.log('props', props)
      testChildClick(' Returns a value to the parent component ')
      //  Only in this way, which is equivalent to react , equivalent to passing 1 A function is given to a child component, and the child component passes the value to the parent component through the function 
    }

    expose({
      testFatherClick
    })

    return () => {
      return (
        <div>
          <button onClick={handelBtn}> Child component passes value to parent component </button>
        </div>
      )
    }
  }
}

export default Child

Summarize


Related articles: