错误
<!DOCTYPE html>
<html>
<div id="app">
<input v-model="counter"></input>
{{ counter }}
</div>
<script src="https://unpkg.com/vue@next"></script>
<script>
import { ref } from 'vue';
const app = Vue.createApp({});
const counter = ref(0)
console.log(counter)
console.log(counter.value)
counter.value++
console.log(counter.value)
.mount('#app')
</script>
</html>
放在html里简单放不行,在js里也不行
import { ref } from 'vue'
const counter = ref(0)
console.log(counter) // { value: 0 }
console.log(counter.value) // 0
counter.value++
console.log(counter.value) // 1
(node:5574) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/Users/ivyone/ref.js:1
import { ref } from 'vue'
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Object.compileFunction (node:vm:352:18)
at wrapSafe (node:internal/modules/cjs/loader:1031:15)
at Module._compile (node:internal/modules/cjs/loader:1065:27)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
[Done] exited with code=1 in 0.124 seconds
用vue create xxx建立了项目以后,建立一个组件,可以
Ref.vue
<template>
<div>ruguo</div>
</template>
<script>
import { ref } from 'vue'
export default ({
setup() {
const counter = ref(0)
console.log(counter) // { value: 0 }
console.log(counter.value) // 0
counter.value++
console.log(counter.value) // 1
console.log(counter.value)
},
})
</script>
这样的。
<template>
<div>
<h1>setup - 组件内使用 Composition API 的入口点</h1>
<p>{{ username }}</p>
</div>
</template>
<script>
export default {
name: "Setup",
props: {
username: { type: String, default: "草莓草莓" },
},
setup(props, ctx) {
console.log("setup");
console.log(props, ctx);
},
beforeCreate() {
console.log("beforeCreate");
},
};
</script>
参考:https://blog.csdn.net/qq_38290251/article/details/111416164
<template>
<div>
<span>{{ count }}</span>
</div>
<div>
<button @click="count ++">Increment count</button>
</div>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const count = ref(0)
return {
count
}
}
}
</script>
ref() — 单值数据响应式
reactive() — 对象数据响应式