三 新的代码组织方式 Composition Api + script setup [一]
作者:互联网
1 一段来自作者的微博。
归纳性描述:
Composition Api 可以让我们更好的组织代码结构 . script setup 本质上是以一种更精简的方式来书写Compositino Api.
2 示例1 : 写个计数器
#在home.vue 加上todoList
<template>
<h1>这是首页</h1>
<Todolist />
</template>
<script setup>
import Todolist from '../components/Todolist.vue'
</script>
//todolist.vue 文件
<template>
<div><h1 @click 'add'>{{count}}</h2></div>
<script setup>
import {ref} from "vue";
let count = ref(1);
function add(){
count.value ++;
}
</script>
</template>
通过这个例子,熟悉了ref 的用法.
3进一步的,将之前的todolist 写成单vue 文件 .
<template>
<div>
<input type="text" v-model="title" @keydown.enter="addTodo" />
<ul v-if="todos.length">
<li v-for="todo in todos">
<input type="checkbox" v-model ="todo.done"/>
<span>{{todo.title}}</span>
</li>
</ul>
<div v-else>暂无数据</div>
<div>全选<input type="checkbox" v-model="allDone">
<span>{{active}}/{{all}}</span>
</div>
</div>
</template>
<script setup>
import {ref, computed} from 'vue';
let title = ref('新的待办');
let todos = ref([{title:'学习vue',done:false}]);
function addTodo()
{
todos.value.push({title:title.value,done:false})
title.value=''
}
let active = computed(() => {return todos.value.filter((v) => !v.done).length});
let all = computed(() => todos.value.length);
let allDone = computed({
get:function() {
return active.value ==0;
},
set:function(value){
todos.value.forEach((todo) => {todo.done = value;});
}
});
</script>
4再重构一下,用一个函数包起来.
<script>
function useTodos()
{
let title = ref('新的待办');
let todos = ref([{title:'学习vue',done:false}]);
function addTodo()
{
todos.value.push({title:title.value,done:false})
title.value=''
}
let active = computed(() => {return todos.value.filter((v) => !v.done).length});
let all = computed(() => todos.value.length);
let allDone = computed({
get:function() {
return active.value ==0;
},
set:function(value){
todos.value.forEach((todo) => {todo.done = value;});
}
});
return {title,todos,addTodo,active,all,allDone};
}
</script>
<script setup>
import {ref, computed} from 'vue';
let {title,todos,addTodo,active,all,allDone} = useTodos();
</script>
标签:vue,title,setup,script,value,Api,let,ref,todos 来源: https://www.cnblogs.com/xuxing126/p/16101148.html