Vue3 使用范例

<script setup>
import { ref, onMounted, computed, watch, defineProps, defineEmits  } from 'vue'

//  父传子
const props = defineProps({
    car: {
      type: String,
      default() {
        return ''
      }
    },
    money: {
      type: Number,
      default() {
        return 0
      }
    }
  })

//  子传父
const emit = defineEmits(['changeMoney'])
const setAction = () => {
  emit('changeMoney', 5)
}


/* 声明变量 */
// reactive 只定义对象
const state = reactive({
msg: '通过'
})
// ref(定义简单类型和对象类型, 修改数据更新视图必须加上.value)
const count = ref(0)
const setCount = ()=>{
   count.value++
}


/* 计算属性 */
const  doubleCount = computed(()=> count.value * 2)


/* watch 监听 */
const x = ref(0)
const y = ref(0)
const obj = ref({ id: 0 })

watch(() => obj.value.id, (count) => {
  console.log(count)
})

watch([x, () => y.value, () => obj.value.id], ([newArray, oldArray]) => {
  console.log(newArray, oldArray)
})

watch(
  () => obj.value.count,
  (newValue, oldValue) => {
    // 注意:`newValue` 此处和 `oldValue` 是相等的
    // *除非* state.someObject 被整个替换了
    console.log(newValue, oldValue)
  },
  { deep: true, immediate: true }
)

// 定义方法
const  clickAction = () => {
     console.log('定义了方法')
}

// 生命周期钩子
onMounted(() => {
  console.log(`The initial count is ${count.value}.`)
})
</script>

<template>
  <button @click="clickAction">Count is: {{ count }}</button>
</template>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容