<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>开发todoList</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root">
<div>
<div>
<input type="text" :value="inputValue" @input="handleInoutValueChange">
<button @click="handleSubmit">提交</button>
</div>
<ul class="nav justify-content-center">
<li v-for="(item, index) in list" :key="index">{{item}}</li>
</ul>
</div>
</div>
<script>
let app = Vue.createApp({
setup(props, context) {
//1
const { ref , reactive} = Vue;
const inputValue = ref(' ');
//3.1定义一个数组
const list = reactive([])
//2
const handleInoutValueChange = (e) => {
// 获取input改变的值,把获取的值给到
inputValue.value = e.target.value
}
// 3点击提交
const handleSubmit = () => {
list.push(inputValue.value)
}
return {
inputValue,
handleInoutValueChange,
handleSubmit,
list
}
}
})
let vm = app.mount('#root')
</script>
</body>
</html>
抛掉传统的
data(){
return {
content:'我是data里面生命的变量哦',
num:1
}
},
method() {
}
不谈性能,我比较喜欢vue2.0,vue3.0加入很多知识点比较新颖
这里看起来代码很乱,这不是我们想看的,接下来我们对上面代码进行优化
<body>
<div id="root">
<div>
<div>
<input type="text" :value="inputValue" @input="handleInoutValueChange">
<button @click="() => addItemToList(inputValue)">提交</button>
</div>
<ul class="nav justify-content-center">
<li v-for="(item, index) in list" :key="index">{{item}}</li>
</ul>
</div>
</div>
<script>
// 关于list操作内容进行封装
const listRelativeEffect = () => {
const {reactive} = Vue;
const list = reactive([])
const addItemToList = (item) => {
list.push(item)
}
return { list , addItemToList }
}
// 关于inputValue操作内容进行封装
const inputRelativeEffect = () => {
const { ref} = Vue;
const inputValue = ref(' ');
const handleInoutValueChange = (e) => {
// 获取input改变的值,把获取的值给到
inputValue.value = e.target.value
}
return {inputValue, handleInoutValueChange}
}
let app = Vue.createApp({
setup(props, context) {
// 流程调度中转
const {list ,addItemToList} = listRelativeEffect();
const {inputValue, handleInoutValueChange} = inputRelativeEffect();
return {
list,addItemToList,
inputValue,handleInoutValueChange
}
}
})
let vm = app.mount('#root')
</script>
</body>
这样看到每一个是一个功能,当某一块出现问题后能快速找到当前功能代码块,缺点:如果对setup这个不熟悉会发现,一个字乱