data methods 的使用
setup 函数
1. 使用Composition API的入口
2. 在beforeCreate之前调用
3. 在setup中没有this
4. 返回对象中的属性可以在模板中使用
<template>
<div class="home">
<h2>{{ title }}</h2>
<p>{{ state.name }}</p>
<button @click="handleClick">handleClick</button>
</div>
</template>
<script>
import {reactive, onMounted} from 'vue';
export default {
name: 'Home',
components: {},
setup() {
const state = reactive({
name: 'hello world!!!',
age: '222'
});
onMounted(() => {
console.log('222 :>> ', 222);
});
function handleClick() {
console.log('handleClick :>> ', 'handleClick');
}
return {
title: '首页',
state,
handleClick
};
}
};
</script>
ref 函数
ref 函数的作用创建并返回一个响应式的引用
<template>
<div class="home">
<h2 @click="handleSetTitle">{{ title }}</h2>
</div>
</template>
<script>
import {reactive, onMounted} from 'vue';
export default {
name: 'Home',
setup() {
const title = ref('hello 首页');
function handleSetTitle() {
title.value = title.value === '哈哈哈' ? 'hello 首页' : '哈哈哈';
}
return {
title: title,
handleSetTitle
};
}
};
</script>