vue实现简单的发表评论案例(存储在localstorage中)

2023-01-13 10:37:46

1.学习父子组件传值,传方法

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link  href="https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="./lib/vue.js"></script>
</head>
<body>
    <div id="app">
        <combox v-on:func="loadComtent"></combox>
        <ul class="list-group">
            <li class="list-group-item" v-for="item in list" v-bind:key="item.id">
                <span class="badge">评论人 :{{item.user}}</span>
                {{item.content}}
            </li>
        </ul>
    </div>

    <template id="templ">
        <div>
            <div class="form-group">
                <label>评论人:</label>
                <input type="text" class="form-control" v-model="user">
            </div>

            <div class="form-group">
                <label>评论内容:</label>
                <textarea class="form-control" v-model="content"></textarea>  
            </div>
            <div class="form-group">
                <input type="button" value="发表" class="btn btn-primary" v-on:click="fabiao">
            </div>
        </div>
    </template>
   <script>
        var comBox={
            template:'#templ',
            data(){
                return{
                    user:'',
                    content:''
                }
            },
            methods:{
                fabiao:function(){
                    var conment={id:Date.now(),user:this.user,content:this.content}
                    var list=JSON.parse(localStorage.getItem('cmts')||'[]')
                    list.push(conment)
                    localStorage.setItem('cmts',JSON.stringify(list))
                    this.user=this.content=''
                    this.$emit('func')
                }
            }
        }
        var vm=new Vue({
            el:"#app",
            data:{
                list:[
                    {id:Date.now(),user:'李白',content:'天生我拆必有用'},
                    {id:Date.now(),user:'战三',content:'天生我拆必有用2'},
                    {id:Date.now(),user:'李四',content:'天生我拆必有用3'}
                ]
            },
            components:{
                combox:
                    comBox
                
            },
            created(){
               this.loadComtent()
            },
            methods:{
                loadComtent:function(){
                    var list=JSON.parse(localStorage.getItem('cmts')||'[]')
                    this.list=list;
                }
            }
        })
    </script>
</body>
</html>
  • 作者:loveking6
  • 原文链接:https://blog.csdn.net/loveking6/article/details/106024526
    更新时间:2023-01-13 10:37:46