美文网首页
vue组件应用

vue组件应用

作者: 夜色001 | 来源:发表于2021-02-20 11:23 被阅读0次

    源码地址:https://gitee.com/XiaoLvXunLian/my-vue.git

    1、创建组件

    方式一:简单html片段

    Vue.component('blog-post', {
      props: ['title'],
      template: '<h3>{{ title }}</h3>'
    })
    

    方式二:vue文件
    所有的vue文件都是一个组件

    <template>
        <div class="confirm-button">
          <button @click="buttonClick">{{prop1||'确认'}},{{prop2}}</button>
        </div>
    </template>
    
    <script>
        export default {
            name: "Confirm",
            // props: ["text"],//父组件传值给子组件
            props: {
                text:'',
                prop1:'',
                prop2:{
                    default:()=>{return '属性2的默认值'},
                    type : String
                }
            },//父组件传值给子组件
            data() {
              return{
                  msg : true
              }
            },
            methods:{
                buttonClick(){
                    this.$emit('message', this.msg);//向父组件传值
                }
            }
        }
    </script>
    
    <style scoped>
    
    </style>
    
    
    image.png

    2、注册组件

    组件需要注册后才可使用,使用时要引入组件。组件注册分为全局注册和局部注册。
    方式一:全局注册

    Vue.component('vTable', vTable)
    
    image.png

    方式二:局部注册

    <template>
      <div class="first-app">{{msg}}
        <confirm text="注册" @message="getMessage" :prop1="prop1"></confirm>
      </div>
    </template>
    
    <script>
        import Confirm from "../sub/Confirm";
        export default {
            name: "First",
    // 组件局部注册
            components:{
                Confirm
            },
            data(){
                return {
                    msg : "This is the first page",
                    prop1 : "故事",
                }
            },
            methods:{
                getMessage(val){
                    alert(val)
                }
            }
        }
    </script>
    
    <style scoped>
    
    </style>
    
    

    3、组件使用

    html标签使用组件名,vue会自动将驼峰命名改为小写加横杠的形式。
    如组件名为vTable,使用时为

    <v-table :data="tableData"
                   :header="tableHeader"
                   :check="false"
                   :radio="true"
                   :isHandle = "false">
          </v-table>
    

    4、组件传值

    父组件向子组件传值
    子组件通过props属性接收,props属性可以有两种写法,子组件可以设置属性的默认值和类型。

    props: ["text"],//父组件传值给子组件
    
            props: {
                text:'',
                prop1:'',
                prop2:{
                    default:()=>{return '属性2的默认值'},
                    type : String
                }
            },//父组件传值给子组件
    

    子组件向父组件传值
    通过this.$emit调用父组件的自定义事件方法进行传值

    methods:{
                buttonClick(){
                    this.$emit('message', this.msg);//向父组件传值
                }
            }
    

    相关文章

      网友评论

          本文标题:vue组件应用

          本文链接:https://www.haomeiwen.com/subject/llytfltx.html