在html中用script引入Vue3库
<script src="https://unpkg.com/vue@next"></script>
一个简单的计数器
<body> <div id="root"></div> <script> Vue.createApp({ data() { return { content: 1 } }, mounted() { setInterval(() => { this.content += 1 }, 1000) }, template: '<div>{{content}}</div>' }).mount('#root') </script></body>
反转字符串
Vue.createApp({ data() { return { content: 'hello world' } }, methods: { handleBtnClick() { this.content = this.content.split('').reverse().join('') } }, template: `<div>{{content}}</div><button v-on:click="handleBtnClick">反转</button>`}).mount('#root')
显示或隐藏
Vue.createApp({ data() { return { show: true } }, methods: { handleBtnClick() { this.show = !this.show } }, template: `<div v-if="show">hello</div><button v-on:click="handleBtnClick">显示/隐藏</button>`}).mount('#root')
v-model数据双向绑定
Vue.createApp({ data() { return { list: [], inputValue: '' } }, methods: { handleBtnClick() { this.list.push(this.inputValue) this.inputValue = '' } }, template: `<input v-model="inputValue"><button v-on:click="handleBtnClick">新增</button><ul><li v-for="(item, index) of list">{{item}} {{index}}</li></ul>`}).mount('#root')
组件
<script> const app = Vue.createApp({ data() { return { list: [], inputValue: '' } }, methods: { handleBtnClick() { this.list.push(this.inputValue) this.inputValue = '' } }, template: ` <input v-model="inputValue"> <button v-on:click="handleBtnClick">新增</button> <ul> <todo-list v-for="(item, index) of list" v-bind:index="index" v-bind:content="item"/> </ul> ` }) app.component('todo-list', { props: ['index', 'content'], template: `<li>{{index}}--{{content}}</li>` }) app.mount('#root') </script>