vue script setup语法糖

我不是女神ヾ 2022-10-14 15:48 342阅读 0赞

创建项目

yarn 安装的 vue3.0+vite+ts

  1. yarn create @vitejs/app my-vue-ts-vite --template vue-ts

示例

这个时候你在App.vue发现这个 script setup语法糖

  1. <template>
  2. <h1><a href="">{
  3. { count }}</a></h1>
  4. <h1>{
  5. {state.data.a}}</h1>
  6. <button @click="count++">count ++</button>
  7. </template>
  8. <script setup> import { ref,defineProps,reactive,watch } from 'vue'; import { helloLog} from '/@/hooks/hello' /* 基本数据类型 引用数据类型(复杂类型) 个人建议 ref初始化变量 ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装, ref定义的数据访问的时候要多一个.value */ const count =ref(0); const state = reactive({ data:{ a:1} }) defineProps({ msg: { type: String, required: true } }) watch(count,(e)=>{ console.log('count变化了:>> ', e); }) function name(params) { console.log('原始html用法 ',helloLog()); } // </script>
  9. <style scoped lang="scss" > h1{ a { color: #42b983; } } label { margin: 0 0.5em; font-weight: bold; } code { background-color: #eee; padding: 2px 4px; border-radius: 4px; color: #304455; } </style>

总结模板

组件

  1. <template>
  2. <div></div>
  3. </template>
  4. <script setup> import { ref,defineProps,reactive,getCurrentInstance } from 'vue'; const internalInstance = getCurrentInstance();//获取当前实例 const route = internalInstance?.appContext.config.globalProperties.$route; /* 基本数据类型 引用数据类型(复杂类型) 个人建议 ref初始化变量 ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装, ref定义的数据访问的时候要多一个.value */ const count =ref(0); const state = reactive({ data:{ a:1} }) defineProps({ msg: { type: String, required: true } }) </script>
  5. <style scoped lang="scss" > </style>

普通页面

  1. <template>
  2. <div>
  3. <HelloWorld/>
  4. </div>
  5. </template>
  6. <script setup> import { ref,defineProps,reactive,getCurrentInstance } from 'vue'; const internalInstance = getCurrentInstance();//获取当前实例 const route = internalInstance?.appContext.config.globalProperties.$route; import HelloWorld from '/@/components/HelloWorld.vue' /* 基本数据类型 引用数据类型(复杂类型) 个人建议 ref初始化变量 ref 和 reactive 本质我们可以简单的理解为ref是对reactive的二次包装, ref定义的数据访问的时候要多一个.value */ const count =ref(0); const state = reactive({ data:{ a:1} }) </script>
  7. <style scoped lang="scss" > </style>

个人评价

script setup语法糖提供了传统html函数使用方式的便利性+组件化开发的效率,组件导入即可使用无需扔到components,需要计算属性引入 watch即可

发表评论

表情:
评论列表 (有 0 条评论,342人围观)

还没有评论,来说两句吧...

相关阅读

    相关 setup语法

    > 提示: vue3.2 版本开始才能使用语法糖! 1、如何使用setup语法糖 > 只需在 script 标签上写上 setup 代码如下(示例): <t