vue3项目开发-知识锦囊

1.store

action 在语法糖setup上如何触发

vue2
this.$store.dispatch("reduceAscync");
vue3
import { useStore } from 'vuex' let store = useStore() store.dispatch('reduceAscync')

 

2. emit

子组件给父组件传值

vue2

// 子组件

<div @click="buttonClick"></div>

// methods buttonClick () { this.$emit('change', '需要传递的内容') } // 父组件 <div @change="click"></div> // methods click (data) { console.log(data) }

vue3

div写法一样 

// 子组件
<script setup>
import {  defineEmits } from 'vue'
const emit = defineEmits(['change'])
const buttonClick = () => {
  emit('change', '需要传递的内容')
}

</script>

// 父组件

const click = (data) => {
  console.log(data)
}

 

3. watch

 

// 侦听一个 getter
const state = reactive({ count: 0 })
watch(
  () => state.count,
  (count, prevCount) => {
    /* ... */
  }
)

// 直接侦听一个 ref
const count = ref(0)
watch(count, (count, prevCount) => {
  /* ... */
})

如果我们想侦听 props 上的属性变化,需要采用第一种写法

import { ref, onMounted, watch } from 'vue'  
watch(
      () => props.option,
      () => {
        render()
      }
    )// 下面的写法不会被触发
    /*  watch(props.name, (count, prevCount) => {
     }) */

如果是watch多个属性呢,需要重复写watch的么?

 

4.vue3:语法糖内的defineProps及defineEmits、defineExpose

https://blog.csdn.net/skyblacktoday/article/details/120879677

 

5.【错误】元素隐式具有 "any" 类型,因为类型为 "any" 的表达式不能用于索引类型

 

 

 在针对对象使用隐藏得索引取值时报错

解决有2个方法

方法1,给对象添加any类型,添加object是不可以

插入一段官网解释

 

方法2:tsconfig配置添加 "suppressImplicitAnyIndexErrors": false

字面上的理解

暂时不知道这样配置其他弊端

 

六、全局事件总线Bus

vue2

// main.js 注册
Vue.prototype.$eventBus = new Vue({}) // 全局事件总线

// 引用
this.$eventBus .$emit() // 派发事件
this.$eventBus .$on() // 监听事件

 

 vue3

需要安装  npm install mitt -s

在view文件下创建bus.js

// 引入全局事件总线
import mitt from 'mitt'
const $mittBus = mitt()
// 方法说明
/* $mittBus.on, // 监听
 $mittBus.off, // 清除
 $mittBus.on // 触发 */
export default $mittBus

需用引用的页面里直接引入bus.js

// 引入全局事件总线
import bus from '@/bus'

const clickPgae = () => {
  // 全局事件
  bus.emit('事件名', false)
}

监听

import bus from '@/bus'
bus.on('closeTab', (ev: any) => {
  console.log(ev)
  // 数据处理

})

特点是需要的页面需要

import bus from '@/bus'

还有其他方式,但我个人觉得这种是最好理解而且比较简洁,其他的方法可参考https://blog.csdn.net/mfxcyh/article/details/124167423

 七、router在引用

import router from '@/router'
    router.push('..')

 

posted @ 2022-04-27 10:39  树叶铃铛  阅读(431)  评论(0编辑  收藏  举报