Example code comparing different syntax formats of vue3

Example code comparing different syntax formats of vue3

The default template method is similar to vue2, using the setup function in the component

// 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('Method for getting the child component', childRef.value)
      // The subcomponent needs to define expose. If not, it needs to be returned. The corresponding function is generally not returned directly. If it is not used on the page, // just expose the required method or value. }

    //Write through the setup function method, need to return, the method used on the page, and the value //If it is a value defined by reactve, the value rendered on the page through deconstruction is not responsive, need to be converted through toRefs, and then deconstructed // ...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 to prevent ctx.attrs from accessing this attribute*/
  /* Some properties set in props will not be displayed in attrs*/

  emits: ['testClick'], //The purpose of setting this is to make sure there is no corresponding custom method on attrs.
  //If peops is set for a subcomponent, the corresponding value cannot be accessed on attrs //arrts has enhanced functionality in vue3, with custom methods, classes, and styles mounted
  //In vue2, the custom method is mounted to $listeners. In vue3, $listeners 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, //Expose custom methods, parent component calls observed//Expose the value of the child component})

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

Write setup in the script tag <script setup>

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

<script setup>
import { ref } from 'vue'
import Child from './Child.vue'
// This way of writing methods and values ​​that are not used on the return export page, what you need to use is to directly deconstruct the corresponding definition on Vue
const childRef = ref(null)

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

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

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

</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 parent component clicks child component')
}

const observed = reactive({
  a: 1
})

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

</script>

<style scoped>
</style>

Rendering through jsx is very close to react, and it is also the way I recommend most. jsx also supports ts, but .vue files are not as well supported as tsx.

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

const Father = {
  setup() {
    // The ref defined in jsx needs to be accessed through .value when used on the page const city = ref('北京')

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

    const childRef = ref(null)

    const handelFather = (add) => {
      //Also by exposing the expose method in the component // 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 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 parent component clicks child component')
    }

    const handelBtn = () => {
      // emit('testChildClick') // This doesn't work in jsx // console.log('props', props)
      testChildClick('return value to parent component')
      // This method is the only way to pass a function to the child component, which passes the value to the parent component through the function.}

    expose({
      testFatherClick
    })

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

export default Child

Summarize

This is the end of this article about the comparison of different syntax formats of vue3. For more relevant vue3 syntax format comparison content, please search 123WORDPRESS.COM's previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

<<:  How to Delete Junk Files in Linux Elegantly

>>:  MySQL quickly obtains the table instance code without primary key in the library

Recommend

Introduction to the use of MySQL pt-slave-restart tool

Table of contents When setting up a MySQL master-...

Detailed explanation of MySQL transaction processing usage and example code

MySQL transaction support is not bound to the MyS...

Implementation steps for installing FTP server in Ubuntu 14.04

Table of contents Install Software Management Ano...

How to implement a binary search tree using JavaScript

One of the most commonly used and discussed data ...

Additional instructions for using getters and actions in Vuex

Preliminary Notes 1.Differences between Vue2.x an...

Share the problem of Ubuntu 19 not being able to install docker source

According to major websites and personal habits, ...

Vue basic instructions example graphic explanation

Table of contents 1. v-on directive 1. Basic usag...

Two ways to install the Linux subsystem in Windows 10 (with pictures and text)

Windows 10 now supports Linux subsystem, saying g...

Summary of MySQL time statistics methods

When doing database statistics, you often need to...

Implementation of Bootstrap web page layout grid

Table of contents 1. How the Bootstrap grid syste...

Getting Started Tutorial on Animating SVG Path Strokes Using CSS3

Without relying on JavaScript, pure CSS is used t...

Analyzing the MySql CURRENT_TIMESTAMP function by example

When creating a time field DEFAULT CURRENT_TIMEST...

Detailed explanation of jQuery's core functions and event handling

Table of contents event Page Loading Event Delega...