Javascript-форум (https://javascript.ru/forum/)
-   Оффтопик (https://javascript.ru/forum/offtopic/)
-   -   Vue' thread 1 (https://javascript.ru/forum/offtopic/58273-vue%27-thread-1-a.html)

Lemme 08.10.2016 19:37

nerv_, например так. http://javascript.ru/forum/offtopic/...tml#post430983

nerv_ 12.10.2016 09:11

Lemme, делай так, как считаешь правильным :) Время тебя рассудит)

nerv_ 21.10.2016 08:04

Почему разработчики GitLab используют Vue.js?

cyber 21.10.2016 17:24

Я так понимаю что бы писать компоненты на es6 через классы, то нужно делать что то такое? (т.е юзать либу vue-class-component)

import Component from 'vue-class-component'

@Component({
  props: {
    propMessage: String
  },
  template: `
    <div>
      <input v-model="msg">
      <p>prop: {{propMessage}}</p>
      <p>msg: {{msg}}</p>
      <p>computed msg: {{computedMsg}}</p>
      <button @click="greet">Greet</button>
    </div>
  `
})
class App {
  // return initial data
  data () {
    return {
      msg: 123
    }
  }

  // lifecycle hook
  mounted () {
    this.greet()
  }

  // computed
  get computedMsg () {
    return 'computed ' + this.msg
  }

  // method
  greet () {
    alert('greeting: ' + this.msg)
  }
}

kobezzza 21.10.2016 17:56

Cyber, как напишешь - таки будет) Я раньше по похожему делал, но хотелось нормального автокомплита, в итоге сделал так:

import iData from '../i-data/i-data';
import * as tpls from './b-button.ss';
import { PARENT } from '../i-block/i-block';
import { model } from '../../core/block';

@model(tpls)
export default class bButton extends iData {
	/**
	 * Button type
	 */
	type: string = 'button';

	/**
	 * Connected form id
	 */
	form: ?string;

	/**
	 * Input autofocus mode
	 */
	autofocus: ?boolean;

	/**
	 * Icon before text
	 */
	preIcon: ?string;

	/**
	 * Icon after text
	 */
	icon: ?string;

	/**
	 * Tooltip text
	 */
	hint: ?string;

	/**
	 * Tooltip position
	 */
	hintPos: ?string;

	/** @override */
	static mods = {
		rounding: [
			'none',
			['small'],
			'normal',
			'big'
		],

		theme: [
			PARENT,
			'dark',
			'light',
			'icon'
		]
	};

	/* @override */
	created() {
		this.initCloseHelpers();
	}
}


Декоратор матчит класс и генерит компонент, а инфа о типах пропсов берётся из Flow аннотаций.

join 22.10.2016 07:10

Гик изучает апи Vue 3.0 .:yes:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>vue.js & dinamics.js | https://jsfiddle.net/yyx990803/y91wy85p/</title>
	
	<style>
	.draggable-header-view {
	  background: #fff url(http://thumbsnap.com/i/YopxPzbo.jpg?1021) no-repeat 0 0;
	  background-size: 100% auto;
	  width: 320px;
	  height: 427px;
	  overflow: hidden;
	  margin: 30px auto;
	  position: relative;
	  font-family: 'Roboto', Helvetica, Arial, sans-serif;
	  color: #fff;
	  font-size: 14px;
	  font-weight: 300;
	  box-shadow: 0 0 5px 1px rgb(178, 97, 44);
	  -webkit-user-select: none;
	  -moz-user-select: none;
	  -ms-user-select: none;
	  user-select: none;
	}
	.draggable-header-view .bg {
	  position: absolute;
	  top: 0;
	  left: 0;
	  z-index: 0;
	}
	.draggable-header-view .header,
	.draggable-header-view .content {
	  position: relative;
	  z-index: 1;
      padding: 0 10px;
	  box-sizing: border-box;
	}
	.draggable-header-view .header {
	  height: 160px;
	}
	.draggable-header-view .content {
	  color: #fff;
	  line-height: 24px;
	  position: absolute;
	  top:0;
	  left:0;
	  right:0;
	  opacity: 0.2;
	}
	.draggable-header-view .content p{
      font-size: 24px;
      margin: 0;
	  opacity: inherit;
	}
	.draggable-header-view .content p span{
	  font-size: inherit;
	}
	.draggable-header-view svg{
	    cursor: -webkit-grab;
	}
	.draggable-header-view svg:active,
	.draggable-header-view svg:focus{
	    cursor: -webkit-grabbing;
	}
	</style>
	
	<script src="https://unpkg.com/vue@latest/dist/vue.js"></script>
	<script src="https://unpkg.com/dynamics.js@1.1.5"></script>
  </head>
  <body>

<!-- template for the component -->
<script type="text/x-template" id="header-view-template">
  <div class="draggable-header-view"
    @mousedown="startDrag" @touchstart="startDrag"
    @mousemove="onDrag" @touchmove="onDrag"
    @mouseup="stopDrag" @touchend="stopDrag" @mouseleave="stopDrag">
    <svg class="bg" width="320" height="460">
	  <path :d="plusPathLeft" fill="#b2612c">Vue.js</path>
	  <path :d="plusPathRight" fill="#b2612c"></path>
    </svg>
    <div class="content" :style="contentPosition">
      <slot name="content"></slot>
    </div>
  </div>
</script>

<div id="app" @touchmove.prevent>
  <draggable-header-view>
    <template slot="content">
      <p>Api <span>V</span><span>u</span><span>e</span><span>.</span><span>j</span><span>s</span> v.3.0</p>
    </template>
  </draggable-header-view>
</div>

<script>
(function(window){
var xuy=110;
Vue.component('draggable-header-view', {
  template: '#header-view-template',
  data: function () {
    return {
      dragging: false,
      c: { x: xuy, y: xuy },
      start: { x: 0, y: 0 }
    }
  },
  computed: {
	plusPathLeft: function(){
	    return 'M'+this.c.x+' '+this.c.y+' h35 v35 h35 v35 h-35 v35 h-35 v-35 h-35 v-35 h35'
	},
	plusPathRight: function(){
	    return 'M'+(this.c.x + 143)+' '+(this.c.y - 60)+' h30 v30 h30 v30 h-30 v30 h-30 v-30 h-30 v-30 h30'
	},
    contentPosition: function () {
      var dy = this.c.y - xuy
      var dampen = dy > 0 ? 2 : 4
      return {
		opacity: (dy/dampen/20)
      }
    }
  },
  methods: {
    startDrag: function (e) {
      e = e.changedTouches ? e.changedTouches[0] : e
      this.dragging = true
      this.start.x = e.pageX
      this.start.y = e.pageY
    },
    onDrag: function (e) {
      e = e.changedTouches ? e.changedTouches[0] : e
      if (this.dragging) {
        this.c.x = xuy + (e.pageX - this.start.x)
        var dy = e.pageY - this.start.y
        var dampen = dy > 0 ? 1.5 : 4
        this.c.y = xuy + dy / dampen
      }
    },
    stopDrag: function () {
      if (this.dragging) {
        this.dragging = false
        dynamics.animate(this.c, {
          x: xuy,
          y: xuy
        }, {
          type: dynamics.spring,
          duration: 1234,
          frequency: 537,
          friction: 200,
          anticipationSize: 120
        })
      }
    }
  }
})

new Vue({ el: '#app' })
})(window);
</script>
  </body>
</html>

cyber 22.10.2016 15:12

Цитата:

Сообщение от kobezzza
Декоратор матчит класс и генерит компонент

а можно по подробней, как он генирирует компонент?)

nerv_ 22.10.2016 21:55

Цитата:

Сообщение от cyber
Я так понимаю что бы писать компоненты на es6 через классы, то нужно делать что то такое? (т.е юзать либу vue-class-component)

Очень похоже на то. Меня тоже раньше на классах клинило :) , на самом деле они там по большому счету не нужны. Представить, что ты описываешь объект, а затем просто передаешь его в функцию --- Vue(descriptor). Иными словами, если ты инкапсулируешь в модули, то модуль будет возвращать descriptor, а не класс.

kobezzza 23.10.2016 13:12

Цитата:

Сообщение от cyber (Сообщение 432606)
а можно по подробней, как он генирирует компонент?)

Ну сперва на этапе трансляции я заменяю:

foo: String = '1';


На

@prop({type: String, default: '1'})
foo;


А дальше главный декоратор model, которым врапится компонент, создаёт экземпляр класса и на его основе делает Vue.component. Конструктор базового класса возвращает объект, где геттеры/сеттеры заменены на компьютеды, поля с декораторыми @prop и @field на props и data(). Методы вставляются в methods, а зарезирвированные слова типа mounted как есть. Также статики становятся свойствами $options Vue. В общем всё довольно просто и главное, что работает автокомплит и super. Еще я для сеттеров и геттеров генерю методы, например fooGetter, чтобы можно было вызывать их через super.

cyber 23.10.2016 14:05

kobezzza, ты написал свой транслятор?


Часовой пояс GMT +3, время: 00:12.