Vue 기본 사항 시작하기(1부)

<script src="https://unpkg.com/vue@next"></script>

DOM 지향 프로그래밍에서 데이터 지향 프로그래밍으로

표시 목록 입력

const app=Vue.createApp({
        data(){
            return{
                inputValue:'',
                list:[]
            }
        },
        methods:{
            handleAddItem(){
                this.list.push(this.inputValue);
                this.inputValue='';
            }
        },
        template:
            `
                <div>
                    <input v-model="inputValue" />
                    <button
                        v-on:click="handleAddItem"
                        v-bind:title="inputValue">
                        增加
                    </button>
                    <ul>
                        <todo-item v-for="(item,index) of list" v-bind:content="item" v-bind:index="index"/>   
                    <ul>    
                </div>
            `
    });

    
    app.component('todo-item',{
        props:['content','index'],
        template:'<li>{
   
   {index}}--{
   
   {content}}</li>'
    });

    app.mount('#root');

역 문자열

    Vue.createApp({
        data(){
            return{
                str:'hello world'
            }
        },
        methods:{
            handleReverse(){
                this.str=this.str.split('').reverse().join('');
            }
        },
        template:
            `
                <div>
                    {
   
   {str}}
                    <button v-on:click="handleReverse">反转字符串</button> 
                </div>
            `

    }).mount('#root');

createApp은 Vue 애플리케이션을 생성하고 앱 변수에 저장하는 것을 의미합니다.

전달된 매개변수는 응용 프로그램의 가장 바깥쪽 구성 요소가 표시되는 방식을 나타냅니다.

MVVM 디자인 패턴, M->모델 데이터, V->보기 보기, VM->ViewModel 보기 데이터 연결

라이프사이클 기능(8)

// 生命周期函数 在某一时刻自动执行的函数
    const app = Vue.createApp({
        data() {
            return {
                message: 'hello world'
            }
        },
        beforeCreate(){
            // 在实例生成之前自动执行的函数
            console.log('beforeCreate');
        },
        created(){
            // 在实例生成之后自动执行的函数
            console.log('created');
        },
        beforeMount(){
            // 在组件内容被渲染到页面之前自动执行的函数
            console.log(document.getElementById('root').innerHTML,'beforeMounted');
        },
        mounted(){
            // 在组件内容被渲染到页面之后自动执行的函数 
            console.log(document.getElementById('root').innerHTML,'mounted');
        },
        beforeUpdate(){
            // 在data中数据发生变化时,自动执行的函数
            console.log(document.getElementById('root').innerHTML,'beforeUpdate');
        },
        updated(){
            // 在data中数据发生变化时,且重新渲染页面后,自动执行的函数
            console.log(document.getElementById('root').innerHTML,'updated');
        },
        beforeUnmount(){
            // 当Vue应用(实例)失效时,自动执行的函数
            console.log(document.getElementById('root').innerHTML,'beforeUnmount');
        },
        unmounted(){
            // 当Vue应用(实例)失效时,且DOM完全销毁之后,自动执行的函数
            console.log(document.getElementById('root').innerHTML,'unmounted');
        },
        template: `<div>{
   
   {message}}</div>`
    });
    const vm=app.mount('#root');

 

보간 표현식{ {}}

const app = Vue.createApp({
        data() {
            return {
                message: '<strong>hello world</strong>'
            }
        },
        template: `<div>{
   
   {message}}</div>`
    });
    const vm=app.mount('#root');

 결과는 html 태그가 포함된 변수를 보여줍니다. 변수를 굵게 표시하려면 템플릿에 v-html 명령을 추가 해야 합니다 .

const app = Vue.createApp({
        data() {
            return {
                message: '<strong>hello world</strong>'
            }
        },
        template: `<div v-html="message"></div>`
    });
    const vm=app.mount('#root');

 

title 속성을 추가하려면 v-bind 명령어를 추가해야 하는데, 이때 페이지에서 hello world 위로 마우스를 가져가면 hello world 제목이 나타납니다.

v-bind: 제목 약어: 제목 

const app = Vue.createApp({
        data() {
            return {
                message: 'hello world'
            }
        },
        template: `<div v-bind:title="message">hello world</div>`
    });
    const vm=app.mount('#root');

입력 상자와 함께 v-bind를 사용할 수도 있습니다.

const app = Vue.createApp({
        data() {
            return {
                disable:false
            }
        },
        template: `<input v-bind:disabled="disable"/>`
    });
    const vm=app.mount('#root');

참고: 템플릿은 v-once 지시문을 사용하여 변수가 처음 값만 렌더링하도록 한 다음 변수 값을 수정하면 변경 사항을 따르지 않습니다. 

이벤트 바인딩 v-on:click() 축약형 @click

동적 속성 결합: [변수] 

const app = Vue.createApp({
        data() {
            return {
                message:'hello world',
                name:'title',
                event:'click'
            }
        },
        methods:{
            handleClick(){
                alert('click');
            }
        },
        template: `<div :[name]="message" @[event]="handleClick">{
   
   {message}}</div>`
    });
    const vm=app.mount('#root');

기본 동작 방지 @click.prevent="handleClick"

const app = Vue.createApp({
        data() {
            return {
                message:'hello world'
            }
        },
        methods:{
            handleClick(){
                alert('click');
                //e.preventDefault();
            }
        },
        template: 
        `
            <form action="http://www.baidu.com" @click.prevent="handleClick">
                <button type="submit">提交</button>
            </form>
        `
    });
    const vm=app.mount('#root');

계산된 계산 속성

const app = Vue.createApp({
        data() {
            return {
                message:'hello world'
            }
        },
        computed:{
            // 当计算属性依赖的内容发生变化时,方法才会重新执行计算
            total(){
                return Date.now();
            }
        },
        methods:{
            // 只要页面重新渲染,方法就会执行
            formatString(string){
                return string.toUpperCase();
            },
            getTotal(){
                return Date.now();
            }
        },
        template: 
        `
            <div>{
   
   {formatString(message)}} {
   
   {total}}</div>
            <div>{
   
   {formatString(message)}} {
   
   {getTotal()}}</div>
        `
    });
    const vm=app.mount('#root');

리스너 감시(일반적으로 비동기 작업에 사용됨)(해당 속성 모니터링)

const app = Vue.createApp({
        data() {
            return {
                message:'hello world',
                count:2,
                price:5,
                newTotal:10
            }
        },
        // 监听器
        watch:{
            // 当价格发生变化才会执行的函数
            price(current,prev){
                this.newTotal= current*this.count;
            }
        },
        computed:{
            // 当计算属性依赖的内容发生变化时,方法才会重新执行计算 建议使用因为有缓存、简洁
            total(){
                return this.price*this.count;
            }
        },
        methods:{
            // 只要页面重新渲染,方法就会执行
            formatString(string){
                return string.toUpperCase();
            },
            getTotal(){
                return this.price*this.count;
            }
        },
        template: 
        `
            <div>{
   
   {formatString(message)}} {
   
   {total}}</div>
            <div>{
   
   {formatString(message)}} {
   
   {getTotal()}}</div>
            <div>{
   
   {formatString(message)}} {
   
   {newTotal}}</div>
        `
    });
    const vm=app.mount('#root');

문자열 스타일 변경

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>lesson 5</title>
    <script src="https://unpkg.com/vue@next"></script>
    <style>
        .red{
            color: red;
        }
        .green{
            color: green;
        }
        .blue{
            color: blue;
        }
        .brown{
            color: brown;
        }
    </style>
</head>
<body>
    <div id="root"></div>
</body>
<script>
    // 改变样式
    // 1字符串/2对象/3数组
    const app = Vue.createApp({
        data(){
            return{
                classString:'green',
                classObject:{
                    'red':true,
                    'green':true,
                    'blue':true
                },
                classArray:['red','blue','green',{brown:true}]
            }
        },
        template: 
        `
            <div :class="classString">Hello World</div>
            <div :class="classArray">Hello World</div>
            <div :class="classObject">Hello World</div>
        `
    });
    const vm=app.mount('#root');
</script>

</html>

상위 요소에는 여러 하위 요소가 포함됩니다. 참고: $attrs.class는 다음을 사용합니다. 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>lesson 5</title>
    <script src="https://unpkg.com/vue@next"></script>
    <style>
        .red{
            color: red;
        }
        .green{
            color: green;
        }
        .blue{
            color: blue;
        }
        .brown{
            color: brown;
        }
    </style>
</head>
<body>
    <div id="root"></div>
</body>
<script>
    // 改变样式
    // 1字符串/2对象/3数组
    const app = Vue.createApp({
        data(){
            return{
                classString:'red',
                classObject:{
                    'red':true,
                    'green':true,
                    'blue':true
                },
                classArray:['red','blue','green',{brown:false}]
            }
        },
        template: 
        `
            <div :class="classString">
                Hello World
                <demo class="green" />
            </div>
        `
    });
    app.component('demo',{
        template:
        `
            <div :class="$attrs.class">one</div>
            <div>two</div>
        `
    });
    const vm=app.mount('#root');
</script>

</html>

인라인 스타일 사용

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>lesson 5</title>
    <script src="https://unpkg.com/vue@next"></script>
    <style>
        .red{
            color: red;
        }
        .green{
            color: green;
        }
        .blue{
            color: blue;
        }
        .brown{
            color: brown;
        }
    </style>
</head>
<body>
    <div id="root"></div>
</body>
<script>
    // 改变样式
    // 1字符串/2对象/3数组
    const app = Vue.createApp({
        data(){
            return{
                classString:'red',
                classObject:{
                    'red':true,
                    'green':true,
                    'blue':true
                },
                classArray:['red','blue','green',{brown:false}],
                styleString:'color:yellow;background:orange',
                // 行内样式我们使用对象存储可读性更高
                styleObject:{
                    color:'orange',
                    background:'purple'
                }
            }
        },
        template: 
        `
            <div :style="styleObject">
                Hello World
            </div>
        `
    });
    app.component('demo',{
        template:
        `
            <div :class="$attrs.class">one</div>
            <div>two</div>
        `
    });
    const vm=app.mount('#root');
</script>

</html>

v-if와 v-show의 차이점

const app = Vue.createApp({
        data(){
            return{
                show:false
            }
        },
        template: 
        `
            <div v-if="show">Hello World</div>
            <div v-show="show">Bye World</div>
        `
    });
    const vm=app.mount('#root');

요소를 자주 수정해야 하는 경우 요소가 파괴되지 않으므로 v-show를 사용하는 것이 좋습니다. 

const app = Vue.createApp({
        data(){
            return{
                conditionOne:false,
                conditionTwo:true
            }
        },
        template: 
        `
            <div v-if="conditionOne">if</div>
            <div v-else-if="conditionTwo">else if</div>
            <div v-else>else</div>
            
        `
    });
    const vm=app.mount('#root');

v-용도

배열 및 객체 사용 참고 : v-for의 우선 순위가 v-if보다 높으므로 판단하려면 태그를 중첩해야 하지만 이때 추가 div 태그가 있음을 발견했습니다. 약간의 트릭을 사용하여 외부 div 태그를 교체합니다 . 템플릿 태그의 자리 표시자와 동일합니다.

const app = Vue.createApp({
        data(){
            return{
                listArray:['dell','lee','teacher'],
                listObject:{
                    firstName:'dell',
                    lastName:'lee',
                    job:'teacher'
                }
            }
        },
        methods:{
            handleAddBtnClick(){
                // 1使用数组的变更函数
                //this.listArray.push('hello');结尾增加
                //this.listArray.pop();结尾删除
                //this.listArray.shift();开头删除
                //this.listArray.unshift('hello');//开头增加
                // this.listArray.reverse();

                // 2直接替换数组
                // this.listArray=['bye','world'];
                // this.listArray=['bye','world'].filter(item=>item==='bye');

                // 3更新数组内容
                // this.listArray[1]='bye';
                this.listObject.age=100;
                this.listObject.sex='male';
            }
        },
        template: 
        `
            <div>
                <template v-for="(value,key,index) in listObject" :key="index">
                    <div v-if="key!=='lastName'">
                        {
   
   {value}}--{
   
   {key}}--{
   
   {index}}
                    </div>
                </template>
                <div v-for="item in 10">{
   
   {item}}</div>
                <button @click="handleAddBtnClick">新增</button>    
            </div>
        `
    });
    const vm=app.mount('#root');

이벤트

여러 함수를 호출할 때 이전과 같이 참조 이름을 직접 작성할 수 없으며 () 쉼표를 추가하여 구분해야 적용됩니다. 

const app = Vue.createApp({
        data(){
            return{
                counter: 0
            }
        },
        methods:{
            handleBtnClick(num,event){
                console.log(event.target);
                this.counter+=num;
            }
        },
        template: 
        `
            <div>
                {
   
   {counter}}
                <button @click="handleBtnClick(2,$event)">新增</button>    
            </div>
        `
    });
    const vm=app.mount('#root');

 

const app = Vue.createApp({
        data(){
            return{
                counter: 0
            }
        },
        methods:{
            handleBtnClick(){
                alert('1');
            },
            handleBtnClick1(){
                alert('2');
            },
        },
        template: 
        `
            <div>
                {
   
   {counter}}
                <button @click="handleBtnClick(),handleBtnClick1()">新增</button>    
            </div>
        `
    });
    const vm=app.mount('#root');

버블링 중지(외부 전파) @click.stop 

const app = Vue.createApp({
        data(){
            return{
                counter: 0
            }
        },
        methods:{
            handleBtnClick(){
                this.counter+=1;
            },
            handleDivClick(){
                alert('div click');
            }
        },
        template: 
        `
            <div>
                {
   
   {counter}}
                <div @click="handleDivClick">
                    <button @click.stop="handleBtnClick">新增</button>    
                </div>
            </div>
        `
    });
    const vm=app.mount('#root');

자신의 레이블을 클릭하여 @click.self를 표시합니다.

const app = Vue.createApp({
        data(){
            return{
                counter: 0
            }
        },
        methods:{
            handleBtnClick(){
                this.counter+=1;
            },
            handleDivClick(){
                alert('div click');
            }
        },
        template: 
        `
            <div>
                <div @click.self="handleDivClick">
                    {
   
   {counter}}
                    <button @click="handleBtnClick">新增</button>    
                </div>
            </div>
        `
    });
    const vm=app.mount('#root');

이벤트 수정자: @click.prevent 레이블은 기본 동작이 발생하는 것을 방지하고, @click.capture 캡처 단계(외부에서 내부로)는 버블링 단계(내부에서 외부로)로 기본 설정되며, @click.once는 클릭만 가능합니다. 한 번

키 및 마우스 수정자

按键:입력,탭,삭제,esc,위,아래,왼쪽,오른쪽

마우스: 왼쪽, 오른쪽, 가운데

const app = Vue.createApp({
        data(){
            return{
                counter: 0
            }
        },
        methods:{
            handleKeyDown(){
                console.log('keydown');
            }
        },
        template: 
        `
            <div>
                <input @keydown.delete="handleKeyDown"/>
            </div>
        `
    });
    const vm=app.mount('#root');
const app = Vue.createApp({
        data(){
            return{
                counter: 0
            }
        },
        methods:{
            handleClick(){
                console.log('click');
            }
        },
        template: 
        `
            <div>
                <div @click="handleClick">123</div>
            </div>
        `
    });
    const vm=app.mount('#root');

양방향 바인딩

확인란 확인란 및 단일 버튼 라디오 

// input,textarea,checkbox,radio
    const app = Vue.createApp({
        data(){
            return{
                message:[]
            }
        },
        template: 
        `
            <div>
                {
   
   {message}}
                jack <input type="checkbox" value="jack" v-model="message"/>
                jessica <input type="checkbox" value="jessica" v-model="message"/>
                karry <input type="checkbox" value="karry" v-model="message"/>
            </div>
        `
    });
    const vm=app.mount('#root');

 

// input,textarea,checkbox,radio
    const app = Vue.createApp({
        data(){
            return{
                message:''
            }
        },
        template: 
        `
            <div>
                {
   
   {message}}
                jack <input type="radio" value="jack" v-model="message"/>
                jessica <input type="radio" value="jessica" v-model="message"/>
                karry <input type="radio" value="karry" v-model="message"/>
            </div>
        `
    });
    const vm=app.mount('#root');

 

리스트 박스

const app = Vue.createApp({
        data(){
            return{
                message:[],
                options:[{
                    text:'A',value:{value:'A'}
                },{
                    text:'B',value:{value:'B'}       
                },{
                    text:'C',value:{value:'C'}
                }]
            }
        },
        template: 
        `
            <div>
                {
   
   {message}}
                <select v-model="message" multiple>
                    <option v-for="item in options" :value="item.value">{
   
   {item.text}}</option>
                </select>
            </div>
        `
    });
    const vm=app.mount('#root');

 

const app = Vue.createApp({
        data(){
            return{
                message:'world',
            }
        },
        template: 
        `
            <div>
                {
   
   {message}}
                <input type="checkbox" v-model="message" true-value="hello" false-value="world"/>
            </div>
        `
    });
    const vm=app.mount('#root');

 world는 선택되지 않은 값을 나타냅니다.

참고: v-model.lazy와 같은 입력 상자에서 마우스를 멀리 이동하고 외부를 클릭하여 양방향으로 바인딩하십시오. v-model-trim은 문자열의 시작과 끝에서 공백을 제거합니다.

 

 

 

 

 

추천

출처blog.csdn.net/bubbleJessica/article/details/130142194