首頁  >  文章  >  web前端  >  什麼是語法糖? Vue3.2中怎麼使用語法糖?

什麼是語法糖? Vue3.2中怎麼使用語法糖?

青灯夜游
青灯夜游轉載
2022-11-28 20:11:241793瀏覽

Vue中怎麼使用語法糖?以下這篇文章帶大家了解一下語法糖,並介紹一下Vue3.2語法糖的使用方法,希望對大家有幫助!

什麼是語法糖? Vue3.2中怎麼使用語法糖?

一. 概述

Vue2時期,元件裡定義的各類別變數、方法、計算屬性等是分別存放到datamethodscomputed等選項裡,這樣編寫的程式碼不便於後期的查閱,查找一個業務邏輯需要在各個選項來回切換。 vue3.0組合式APIsetup函數的推出就是為了解決這個問題,它讓我們的邏輯關注點更加集中,語法也更加精簡,但是當我們在使用vue3.0的語法就建構元件的時候,總是需要把外面定義的方法變數必須要return出去才能在d477f9ce7bf77f53fbcf36bec1b69b7a,比較麻煩一些. vue3. 2語法糖的出現以及一些新增的API,讓我們的程式碼進一步簡化。 【學習影片分享:vue影片教學web前端影片

什麼是文法糖?

語法糖(英文:Syntactic sugar)是由英國電腦科學家彼得·蘭丁發明的術語,指電腦語言中加入的某種語法,這種語法對語言的功能沒有影響,但是更方便程式設計師使用。語法糖讓程式更加簡潔,有更高的可讀性。

Vue3.2語法糖

#請看下vue3.0vue3.2的單一檔案元件(SFC,即.vue 檔案)的結構比較

  • #vue3.0元件
<template>
    <div>
    </div>
</template>
<script>
export default {
    components: {
    },
    props: {
    },
    setup () {
        return {}
    }
}
</script>
<style scoped>
</style>
  • vue3.2元件
<template>
    <MyTestVue :title="title" @click="changeTitle" />
</template>
<script setup>
import MyTestVue from &#39;./MyTest.vue&#39;;
import { ref } from &#39;vue&#39;;
const title = ref(&#39;测试一下&#39;)
const changeTitle = () => {
    title.value = &#39;Hello,World&#39;
}
</script>
<style scoped>
</style>
  • #對比vue3.0vue3.2版本的元件模板,最主要的變化是3.2中沒有了setup函數,而是把它放在了script標籤中。

  • 我們定義的屬性和方法也不用在return中返回,直接就可以用在模板語法中 ...

    這些是直覺的變化,接下來我們學習具體的用法。

二.使用介紹

#1.元件註冊

vue3.0中使用元件,需要使用components 選項來明確註冊:

<script>
import ComponentA from &#39;./ComponentA.js&#39;

export default {
  components: {
    ComponentA
  },
  setup() {
    // ...
  }
}
</script>

vue3.2 5101c0cdbdc49998c642c71f6b6410a8 的在單一檔案元件中,匯入的元件可以直接在範本中使用,元件會自動註冊,且無需指定目前元件的名字,它會自動以檔案名稱為主,也就是不用再寫name屬性了。

<script setup>
import ComponentA from &#39;./ComponentA.vue&#39;
</script>

<template>
  <ComponentA />
</template>

2.Props 宣告

#在vue3.0中,prop可以使用props選項來宣告

<script>
export default {
  props: [&#39;foo&#39;],
  // 或者用这种方式指类型与默认值
  // props: {
  //   foo:{
  //     type: String,
  //     default: &#39;&#39;
  //   },
  // },
  setup(props) {
    // setup() 接收 props 作为第一个参数
    console.log(props.foo)
  }
}
</script>

vue3.2元件中,props可以使用defineProps()巨集來聲明

<script setup>
const props = defineProps([&#39;foo&#39;])
// 或者
const propsOther = defineProps({
  title: String,
  likes: Number
})

console.log(props.foo)
</script>

注意事項:所有的props 都遵循著單向綁定原則,props 因父元件的更新而變化,自然地將新的狀態向下流往子元件,而不會逆向傳遞,這意味著你不應該在子元件中去更改一個prop。

3.計算屬性

我們一般使用計算屬性來描述依賴響應式狀態的複雜邏輯。說白了就是這個計算屬性的值依賴其他響應式屬性的值,依賴的屬性會發生變化,那麼這個計算屬性的值就會重新計算。

<script setup>
import { ref, computed } from &#39;vue&#39;

const firstName = ref(&#39;John&#39;)
const lastName = ref(&#39;Doe&#39;)

const fullName = computed({
  // getter
  get() {
    return firstName.value + &#39; &#39; + lastName.value
  },
  // setter
  set(newValue) {
    // 注意:我们这里使用的是解构赋值语法
    [firstName.value, lastName.value] = newValue.split(&#39; &#39;)
  }
})
</script>

當呼叫fullName.value = 'John Doe'時,setter會被調用,而firstNamelastName會被更新,在vue3.2中我們可以直接在d477f9ce7bf77f53fbcf36bec1b69b7a標籤中使用它,而沒有在需要return回傳。

  • 不要在计算函数中做异步请求或者更改 DOM!
  • 一个计算属性仅会在其响应式依赖更新时才重新计算,如果他依赖的是个非响应式的依赖,及时其值发生变化,计算属性也不会更新。
  • 相比于方法而言,计算属性值会基于其响应式依赖被缓存,一个计算属性仅会在其响应式依赖更新时才重新计算

4. watch

在组合式API中,我们可以使用watch函数在每次响应式状态发生变化时触发回调函数,watch的第一个参数可以是不同形式的“数据源”:它可以是一个 ref(包括计算属性)、一个响应式对象、一个 getter 函数、或多个数据源组成的数组:watch()是懒执行的:仅当数据源变化时,才会执行回调,例如:

<script setup>
import { ref,watch } from &#39;vue&#39;;

const props = defineProps({
    title: String,
    itemList: {
        type: Array,
        default: () => [{
            text: &#39;title&#39;,
            value: 0
        }]
    }
})

watch(() => props.itemList.length,(newValue,oldValue) => {
    console.log(&#39;newValue===&#39;,newValue);
    console.log(&#39;oldValue===&#39;,oldValue);
})
</script>

这里监听props.itemList.length,当传入的itemList数量发生变化时,后面的回调方法会被调用。当然wacth()还有第三个可选参数:否开启深监听(deep), 如果这里这样写:

<script setup>
import { ref,watch } from &#39;vue&#39;;
...
watch(() => props.itemList,(newValue,oldValue) => {
    console.log(&#39;newValue===&#39;,newValue);
    console.log(&#39;oldValue===&#39;,oldValue);
})
</script>

当传入的itemList数量发生改变时,回调函数不会触发,正确的写法是加上其第三个参数deep:true

<script setup>
import { ref,watch } from &#39;vue&#39;;
...
watch(() => props.itemList,(newValue,oldValue) => {
    console.log(&#39;newValue===&#39;,newValue);
    console.log(&#39;oldValue===&#39;,oldValue);
},{deep:true})
</script>

watch也可以同时监听多个属性:

<script setup>
import { ref,watch } from &#39;vue&#39;;

const props = defineProps({
    title: String,
    itemList: {
        type: Array,
        default: () => [{
            text: &#39;title&#39;,
            value: 0
        }]
    }
})
// 同时监听多个属性
watch(() => [props.itemList,props.title],(newValue,oldValue) => {
    console.log(&#39;newValue===&#39;,newValue);
    console.log(&#39;oldValue===&#39;,oldValue);
},{deep:true})
  
</script>

5. watchEffect()

watch()的懒执行不同的是,watchEffect()会立即执行一遍回调函数,如果这时函数产生了副作用,Vue会自动追踪副作用的依赖关系,自动分析出响应源。上面的例子可以重写为:

<script setup>
  ...
watchEffect(() => {
    console.log(&#39;itemList===&#39;,props.itemList.length);
    console.log(&#39;title===&#39;,props.title);
})
</script>

这个例子中,回调会立即执行。在执行期间,它会自动追踪props.itemList.length作为依赖(和计算属性的行为类似)。每当传入的itemList.length变化时,回调会再次执行。

如果要清除watchEffect()的的监听,只需要显示的调用watchEffect()的返回函数就可以了,例如:

<script setup>
  ...
const stopEffect = watchEffect(() => {
    console.log(&#39;itemList===&#39;,props.itemList.length);
    console.log(&#39;title===&#39;,props.title);
})
stopEffect()
</script>

watch 只追踪明确侦听的数据源。它不会追踪任何在回调中访问到的东西。另外,仅在数据源确实改变时才会触发回调。我们能更加精确地控制回调函数的触发时机。 watchEffect,则会在副作用发生期间追踪依赖。它会在同步执行过程中,自动追踪所有能访问到的响应式属性。

6.组件的事件调用

6.1 子组件调用父组件的方法

vue3.0中如果我们的子组件触发父组件的方法,我们的做法:

子组件
<script>
export default {
  emits: [&#39;inFocus&#39;, &#39;submit&#39;],
  setup(props, ctx) {
    ctx.emit(&#39;submit&#39;,params)
  }
}
// 或者将可以将emit解构使用
export default {
    setup(props,{emit}) {
    emit(&#39;submit&#39;,params)
  }
}
</script>
父组件
<template>
    <Children @submit="submitHandel"/>
  </div>
</template>

<script>
export default {
  name: &#39;TodoItem&#39;,
  setup(props, { emit }) {
    const submitHandel = () => {
      console.log(&#39;子组件调用了父组件的submitHandel方法&#39;);
    }
    return {
      submitHandel,
    }
  }
};
</script>

vue3.2语法糖中,子组件要触发的事件需要显式地通过 defineEmits() 宏来声明

子组件
<script setup>
const emit = defineEmits([&#39;inFocus&#39;, &#39;submit&#39;])

function buttonClick(parmas) {
  emit(&#39;submit&#39;, parmas)
}
</script>
父组件
<template>
    <Children @submit="submitHandel"/>
  </div>
</template>

<script setup>
  const submitHandel = () => {
    console.log(&#39;子组件调用了父组件的submitHandel方法&#39;);
  }
};
</script>
6.2 父组件调用子组件的方法或是属性

vue3.0中如果父组件触发子组件的方法或是属性,直接在return函数中返回就可以,数据都是默认隐式暴露给父组件的。

<script>
// 子组件
setup(props, { emit }) {
  const isShow = ref(false)
  // 父组件调用这个方法
  const showSubComponent = () => {
    isShow.value = !isShow.value
  }
  return {
      // return 返回
      showSubComponent,
    }
  }
</script>

父组件中通过ref获取到子组件,并对子组件暴露的方法进行访问

父组件
<template>
  <div class="todo-list">
    <TodoItemVue :itemList="itemList" @clickItemHandel="clickItemHandel" ref="todoItemVueRef" />
  </div>
</template>
<script>
  import { ref } from &#39;vue&#39;;
  export default {
  setup(props, { emit }) {
    //获取子组件ref
    const todoItemVueRef = ref(null)
    // 调用子组件的方法
    const callItemFuncHandel = () => {
        todoItemVueRef.value.showSubComponent()
    }
    return {
     todoItemVueRef
    }
  }
};
</script>

vue3.2语法中,父组件的调用方式相同,子组件通过defineExpose()将方法或是属性暴露出去

子组件
<script setup>
const isShow = ref(false)
// 父组件调用这个方法
const showSubComponent = () => {
    isShow.value = !isShow.value
}
// 通过defineExpose将方法暴露出去
defineExpose({
    showSubComponent
})
</script> 
父组件
<template>
  <div class="todo-list">
    <TodoItemVue :itemList="itemList" @clickItemHandel="clickItemHandel" ref="todoItemVueRef" />
  </div>
</template>
<script setup>
  import { ref } from &#39;vue&#39;;
  //获取子组件ref
  const todoItemVueRef = ref(null)
  // 调用子组件的方法
  const callItemFuncHandel = () => {
      todoItemVueRef.value.showSubComponent()
  }
</script>

7.Vuex的使用

vue3.0vue3.2中创建Vuex没有区别,只不过在d477f9ce7bf77f53fbcf36bec1b69b7a模板中使用Vuex的store有细微差别。

import { createStore } from &#39;vuex&#39;;
import { ADD_ITEM_LIST, REDUCE_ITEM_LIST, CHANGE_ITEM_LIST_ASYNC } from &#39;./constants&#39;;

export default createStore({
  state: {
    itemList: [
      { text: &#39;Learn JavaScript&#39;, done: true },
      { text: &#39;Learn Vue&#39;, done: false },
      { text: &#39;Build something awesome&#39;, done: false },
    ],
  },
  getters: {
    doneItemList: (state) => state.itemList.filter((todo) => todo.done),
  },
  mutations: {
    // 使用ES2015风格的计算属性命名功能 来使用一个常量作为函数名
    [ADD_ITEM_LIST](state, item) {
      console.log(&#39;增加数据&#39;, item);
      state.itemList.push(item);
    },
    [REDUCE_ITEM_LIST](state) {
      console.log(&#39;减少数据&#39;);
      state.itemList.pop();
    },
  },
  actions: {
    [CHANGE_ITEM_LIST_ASYNC]({ commit, state }, todoItem) {
      /// 模拟网络请求
      setTimeout(() => {
        commit(ADD_ITEM_LIST, todoItem);
        console.log(&#39;state===&#39;, state);
      }, 1000);
    },
  },
  modules: {
  },
});

vue3.0中我们一般在return中对store.state进行解构,然后可以直接在d477f9ce7bf77f53fbcf36bec1b69b7a中使用state中的值

<template>
  <div class="todo-item">
    <ol>
      <li v-for="(item,index) in itemList" :key="index" class="todos" @click="clickItem(index)">
        {{ item.text }}
      </li>
    </ol>
  </div>
</template>
<script>
  export default {
  name: &#39;TodoItem&#39;,
  setup(props, { emit }) {
    return {
      // 对store.state进行解构
      ...store.state,
      clickItem,
      count,
      isShow,
      showSubComponent,
    }
  }
};
</script>

vue3.2中没有了return,需要我们显示的获取要使用的stare的值

<template>
  <div class="todo-item">
    <ol>
      <li v-for="(item,index) in itemList" :key="index" class="todos" @click="clickItem(index)">
        {{ item.text }}
      </li>
    </ol>
  </div>
</template>
<script setup>
import { useStore } from &#39;vuex&#39;;
const store = useStore()
// 获取后在<template>中使用
const itemList = store.state.itemList
</script>

8. <span style="font-size: 18px;">c9ccee2e6ea535a969eb3f532ad9fe89</span>中的 v-bind

c9ccee2e6ea535a969eb3f532ad9fe89中的 v-bind: 用于在 SFC c9ccee2e6ea535a969eb3f532ad9fe89 标签中启用组件状态驱动的动态 CSS 值

<script setup>
import { ref, watchEffect } from &#39;vue&#39;;
const color = ref(&#39;black&#39;)
const callChangeColorHandel = () => {
  if(color.value === &#39;black&#39;) {
    color.value = &#39;red&#39;
  }else {
    color.value = &#39;black&#39;
  }
}
</script>
<style lang="scss" scoped>
.todo-list {
  color: v-bind(color);
}
</style>

触发callChangeColorHandel 函数,在c9ccee2e6ea535a969eb3f532ad9fe89中的v-bind指令可以动态绑定的响应式状态。

三. 總結

整體來說,setup語法糖的引入簡化了使用Composition API時冗長的模板程式碼,也就是讓程式碼更加簡潔,可讀性也更高。並且官方介紹vue3.2在介面渲染的速度以及記憶體的使用量上都進行了優化,本文只是對setup語法糖的常用方式進行了總結,更多vue3.2新功能可以去官方文件查看。

(學習影片分享:web前端開發程式設計基礎影片

以上是什麼是語法糖? Vue3.2中怎麼使用語法糖?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.cn。如有侵權,請聯絡admin@php.cn刪除