关于前端:vue3与vue2使用的一些对比

39次阅读

共计 3233 个字符,预计需要花费 9 分钟才能阅读完成。

最近在尝试应用 vue3,整顿了一些和 vue2 在应用上的一些区别

1. 代码构造变动

1.1 vue2script 构造

<template>
  <div>
  </div>
</template>

<script>
export default {
  name: '',
  components: {},
  props: {},
  data() {return {}
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {}}
</script>

<style  lang="scss" scoped></style>

1.2 vue3script 构造

<template> </template>
<script lang="ts">
  import {defineComponent, onMounted, reactive, UnwrapRef, watch} from 'vue';

  interface State {}
  export default defineComponent({
    name: 'components name',
    props: {},
    setup(props) {console.log('props:', props);
      //data
      const state: UnwrapRef<State> = reactive({});

      //Lifecycle Hooks
      onMounted(() => {});
      //watch
      watch(() => props,
        (_count, _prevCount) => {},
        {
          deep: true,
          immediate: true,
        }
      );
      //methods
      const getList = () => {};
      
      return {
        state,
        getList
      };
    },
  });
</script>
<style lang="scss" scoped></style>

因为 setup 是围绕 beforeCreate 和 created 生命周期钩子运行的,所以不须要显式地定义它们。换句话说,在这些钩子中编写的任何代码都应该间接在 setup 函数中编写。

下表蕴含如何在 setup () 外部调用生命周期钩子:

选项式 API Hook inside setup
beforeCreate Not needed*
created Not needed*
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeUnmount onBeforeUnmount
unmounted onUnmounted
errorCaptured onErrorCaptured
renderTracked onRenderTracked
renderTriggered onRenderTriggered

2. 变量的申明与赋值

//import {ref} from 'vue';
const count = ref(0)
console.log(count.value) // 0

count.value++
console.log(count.value) // 1

变量的申明有点相似于 reactState Hook

3. 对象 / 数组的申明与赋值(响应性)

举荐应用 reactive 包裹数组,

//import {reactive} from 'vue';
const state = reactive({arr: []
});

state.arr = [1, 2, 3]

或者

const state = ref([])

state.value = [1, 2, 3]

或者

const arr = reactive([])

arr.push(...[1, 2, 3])

这几种方法都能够触发响应性,而后界面中失常应用 v-for 即可,举荐第一种

4. props/$emit

父子组件传值的写法

  • 父组件
<Search @searchData="searchData" :quaryParams="quaryParams"/>

父组件的写法和 vue 还是一样的,只是子组件须要作一些扭转

  • 子组件
<script lang="ts">
import {defineComponent} from 'vue';
interface GetUserListParams {
    pageNum: number;
    pageSize: number;
    roleName: string;
}
export default defineComponent({
    name: 'Search',
    props: {
        quaryParams: {
            type: Object as PropType<GetUserListParams> ,
            default: () = > ({
                pageNum: 1,
                pageSize: 10,
                roleName: ''
            })
        }
    },
    emits: ['searchData'],// 须要申明 emits
    setup(_props, context) {const onSubmit = () => {context.emit('searchData', "我是子节点传递给父节点的值");
      }
      
      return {getData}
    }
});
</script>

5. Provide / Inject

5.1 vue2写法

  • 父组件
<!-- src/components/MyMap.vue -->
<template>
  <MyMarker />
</template>

<script>
import MyMarker from './MyMarker.vue'

export default {
  components: {MyMarker},
  provide: {
    location: 'North Pole',
    geolocation: {
      longitude: 90,
      latitude: 135
    }
  }
}
</script>
  • 子组件
<!-- src/components/MyMarker.vue -->
<script>
export default {inject: ['location', 'geolocation']
}
</script>

5.2 vue3写法

  • 父组件
<!-- src/components/MyMap.vue -->
<template>
  <MyMarker />
</template>

<script>
import {provide, reactive, ref} from 'vue'
import MyMarker from './MyMarker.vue

export default {
  components: {MyMarker},
  setup() {const location = ref('North Pole')
    const geolocation = reactive({
      longitude: 90,
      latitude: 135
    })

    provide('location', location)
    provide('geolocation', geolocation)
  }
}
</script>
  • 子组件
<!-- src/components/MyMarker.vue -->
<script>
import {inject} from 'vue'

export default {setup() {const userLocation = inject('location', 'The Universe')
    const userGeolocation = inject('geolocation')

    return {
      userLocation,
      userGeolocation
    }
  }
}
</script>

更多可浏览 Provide / Inject

6. watch

  • vue2
watch: {
    count: {handler: function(val, oldval) {},
      immediate: true,
      deep: true
    }
}
  • vue3
 setup() {const count = ref(0)
     // 监听 count
     watch(() = > count, (_count, _prevCount) = > {}, {
             deep: true,
             immediate: true
         }
     );
 }

后续遇到其余问题缓缓补充

正文完
 0