! 제품 버전을 정확하게 입력해 주세요.
제품 버전이 정확하게 기재되어 있지 않은 경우,
최신 버전을 기준으로 안내 드리므로
더욱 빠르고 명확한 안내를 위해
제품 버전을 정확하게 입력해 주세요!

Vue 애플리케이션에서 Wijmo 컨트롤의 테마 및 현지화 설정하기 > 블로그 & Tips

본문 바로가기

Vue 애플리케이션에서 Wijmo 컨트롤의 테마 및 현지화 설정하기

페이지 정보

작성자 GrapeCity 작성일 2020-04-22 00:00 조회 5,674회 댓글 0건

본문

첨부파일

Vue는 Angular 및 React와 유사한 JavaScript 애플리케이션 프레임워크이지만 상당히 가볍습니다. 작은 설치 공간에도 불구하고 Vue는 강력하고 유연한 프레임워크입니다. Wijmo의 JavaScript UI 컴포넌트 라이브러리도 작고 강력하며 유연합니다. 두 라이브러리는 잘 호환됩니다.


Wijmo는 문화라고 하는 40개 이상의 지역과 25가지의 기본 제공 테마를 갖추고 있습니다. 기본적으로 Wijmo는 미국 영어 문화를 사용하여 데이터를 형식화하고 구문 분석합니다. 애플리케이션이 다른 문화권을 대상으로 하는 경우 해당 Wijmo 문화 파일에 대한 참조를 포함해야 합니다.


아래에서는 Wijmo 컨트롤을 사용하여 샘플 Vue 애플리케이션을 만듭니다. 그런 다음 정적 및 동적 메소드를 사용하여 Vue 애플리케이션에서 Wijmo 테마 및 문화를 변경하는 방법을 간략하게 설명합니다.


Wijmo 컨트롤을 사용하여 샘플 Vue 애플리케이션 만들기


Vue CLI를 사용하여 기본 설정으로 프로젝트를 작성합니다.


vue create wijmo-sample
cd wijmo-sample


Vue CLI 애플리케이션 작성에 대한 자세한 내용은 여기를 참조하세요.


프로젝트에 Wijmo를 추가합니다.


yarn add @grapecity/wijmo.vue2.all


Vue CLI 프로젝트를 수정하는 방법


  1. Wijmo 컨트롤에 대한 샘플 데이터를 형성하는 "src/data.js" 파일을 작성합니다.
     
export const countries = [
  'US',
  'Germany',
  'UK',
  'Japan',
  'Italy',
  'Greece',
];

export const data = [];
for (let i = 0; i < countries.length; i++) {
  data.push({
    country: countries[i],
    downloads: Math.round(Math.random() * 20000),
    sales: Math.random() * 10000,
    expenses: Math.random() * 5000
  })
}

  1. 임의의 샘플 데이터가 있는 여러 Wijmo 컨트롤이 포함된 "src/components/WijmoSample.vue" 컴포넌트 파일을 작성합니다.
     
<template>
  <div class="wijmo-sample">  
    <h1>Wijmo controls sample</h1>
    <p>
      <strong>ComboBox:</strong><br />
      <wj-combo-box :itemsSource="countries" />
    </p>
    <p>
      <strong>InputNumber:</strong><br />
      <wj-input-number :value="1234.5678" :step="1" />
    </p>
    <p>
      <strong>InputDate:</strong><br />
      <wj-input-date />
    </p>
    <p>
      <strong>Calendar:</strong><br />
      <wj-calendar />
    </p>
    <p>
      <strong>FlexGrid:</strong><br />
      <wj-flex-grid :itemsSource="data">
        <wj-flex-grid-column binding="country" header="Country" />
        <wj-flex-grid-column binding="downloads" header="Downloads" />
        <wj-flex-grid-column binding="sales" header="Sales" format="c0" />
        <wj-flex-grid-column binding="expenses" header="Expenses" format="c0" 
/>
      </wj-flex-grid>
    </p>
  </div><
</template>

<script>
import * as dataSource from '../data';
import "@grapecity/wijmo.styles/wijmo.css";
import "@grapecity/wijmo.vue2.input";
import "@grapecity/wijmo.vue2.grid";

export default {
  name: 'WijmoSample',
  data: function () {
    return {
      data: dataSource.data,
      countries: dataSource.countries,
    };
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.wijmo-sample {
  width: 50em;
  margin: 3em auto;
}
.wj-calendar {
  width: 25em;
}
</style>

  1. 불필요한 컴포넌트를 이전에 작성된 WijmoSample 컴포넌트로 바꾸어 표준 Vue 템플릿(src/App.vue) 파일을 수정합니다.

<template>
<div id="app">
  <WijmoSample />
</div>
</template>


<script>
import WijmoSample from './components/WijmoSample.vue'

export default {
  name: 'App',
  components: {
    WijmoSample,
  }
}
</script>


  1. 사용하지 않는 "src/assets" 폴더 및 "src/components/HelloWorld.vue" 파일을 제거합니다.

  2. 샘플 애플리케이션을 실행합니다.


yarn serve


  1. 브라우저에서 http://localhost:8080/ 로 이동합니다. 기본 테마 및 로케일을 사용하여 Wijmo 컨트롤을 봅니다.



 


정적 및 동적 메소드 데모를 위한 기초로 이 샘플 애플리케이션을 사용할 수 있습니다.


Vue 애플리케이션에서 정적 메서드 사용


정적 내장 테마 또는 로케일을 사용하려면 필요한 CSS 또는 js 파일을 가져와야 합니다. 기본 제공 테마 또는 organic 테마를 적용 할 수 있습니다.


@grapecity/wijmo.styles 모듈의 themes 폴더에서 기본 제공 테마를 찾습니다.


  • 기본 제공 테마 적용 : @grapecity/wijmo.styles/wijmo.css 대신 적절한 CSS 파일 가져오기
  • organic 테마 적용 : 줄을 바꾸어 src / components / WijmoSample.vue 파일 수정
     
// replace this line
// import "@grapecity/wijmo.styles/wijmo.css";
// by
import "@grapecity/wijmo.styles/themes/wijmo.theme.organic.css";


모듈에서 내장 로케일을 찾습니다 .@grapecity/wijmo.cultures


  • 내장 로케일 적용 : Wijmo를 로드한 후 적절한 js 파일을 가져옵니다. 예를 들어, 일본어 로케일을 로드하려면 다음 행을 가져오기 중 마지막 행으로 추가합니다.
     
// import Japanese locale
import "@grapecity/wijmo.cultures/wijmo.culture.ja";


결과 파일<script> import"_ part of "_src/components/WijmoSample.vue"은 다음과 같습니다.


<script>
import * as dataSource from '../data';
import "@grapecity/wijmo.styles/themes/wijmo.theme.organic.css";
import "@grapecity/wijmo.vue2.input";
import "@grapecity/wijmo.vue2.grid";
import "@grapecity/wijmo.cultures/wijmo.culture.ja";

export default {
  name: 'WijmoSample',
  data: function () {
    return {  
      data: dataSource.data,
      countries: dataSource.countries,
    };
  }
}
</script>


애플리케이션의 모양은 다음과 같습니다.



 


Vue 애플리케이션에서 동적 메소드 사용


동적 테마 및 현지화에는 다음이 필요합니다.


  • 적절한 리소스 (css 및 js 파일)를 동적으로 로드
  • 리소스를 게시하고 필요한 리소스를 즉시 로드합니다. 예를 들어, 테마 또는 로케일 선택기 변경
     

리소스 게시


가장 효율적인 리소스 게시 방법은 웹팩 구성입니다. 웹팩을 구성하면 다음과 같은 이점이 있습니다.


  1. 모든 빌드에서 GrapeCity 모듈에서 지정된 dist 폴더의 지정된 하위 폴더로 리소스가 자동 복사됩니다.
  2. 하위 폴더 이름은 하드 코딩되지 않습니다. (나중에 쉽게 변경할 수 있음)
  3. root에 배포되지 않은 경우 애플리케이션이 작동합니다.
  4. 적절한 폴더의 내용에 따라 동적으로 형성된 사용 가능한 테마 및 로케일 목록


이러한 목표를 달성하기 위해 프로젝트 root에 vue.config.js" 파일을 컨텐츠로 만듭니다.


const path = require('path');
const glob = require('glob');



// public folder name for wijmo themes styles
const wijmoThemesPublicFolder = 'themes';

// public folder name for wijmo cultures
const wijmoCulturesPublicFolder = 'cultures';

// resources source folders
const wijmoThemesSrcFolder = path.resolve('./node_modules/@grapecity/wijmo.styles/themes');
const wijmoCulturesSrcFolder = path.resolve('./node_modules/@grapecity/wijmo.cultures');

// list of available themes
const themes = glob
    .sync('wijmo.theme.*.css', { cwd: wijmoThemesSrcFolder })
    .map(file => file.replace(/^wijmo\.theme\.(.+)\.css$/, '$1'))
    .sort();
themes.unshift('default');

// list of available cultures
const cultures = glob
  .sync('wijmo.culture.*.js', { cwd: wijmoCulturesSrcFolder })
  .map(file => file.replace(/^wijmo\.culture\.(.+)\.js$/, '$1'))
  .sort();

module.exports = {
  chainWebpack: config => {
    // configure DefinePlugin
    config.plugin('define').tap(definitions => {  
      // define process.env variables to use in application at runtime
      const env = definitions[0]['process.env'];
      env.WIJMO_THEMES_PUBLIC_FOLDER = JSON.stringify(wijmoThemesPublicFolder);
      env.WIJMO_CULTURES_PUBLIC_FOLDER = JSON.stringify(wijmoCulturesPublicFolder);
      env.WIJMO_THEMES = JSON.stringify(themes);
      env.WIJMO_CULTURES = JSON.stringify(cultures);

      return definitions;

    });

    // configure CopyWebpackPlugin
    config.plugin('copy').tap(args => {
      // copy wijmo themes
      args[0].push({
        context: wijmoThemesSrcFolder,
        from: '*.css',
        to: path.resolve('./dist/' + wijmoThemesPublicFolder),
      });
      // copy wijmo cultures
      args[0].push({
        context: wijmoCulturesSrcFolder,
        from: '*.js',
        to: path.resolve('./dist/' + wijmoCulturesPublicFolder),
      });

      return args;

    })
  }
}


동적 리소스 로딩


다음과 같이 이러한 요소 중 하나 ( css를 위한 <link>js를 위한 <script>)를 문서 헤드의 HTML에 동적으로 추가하합니다.


  • CSS 파일 (이전에 제거 할 요소를 식별하기 위해 추가된 id 속성) :

<link type="text/css" rel="stylesheet" href="public-path-to-css-file" id="css-resourse-id" />
  • JS 파일 :

<script type="text/javascript" src="public-path-to-js-file" id="js-resourse-id"></script>


테마 또는 로케일을 로드하려면 Wijmo 컨트롤을 다시 렌더링하기 위해 추가 단계가 필요합니다. Control Wijmo 기본 클래스의 invalidateAll 정적 메소드를 사용하여 다시 렌더링합니다.


추가된 <link> 또는 <script>요소의 onload 이벤트에서 프로세스를 호출해야 합니다 .


요소 조작을 단순화하기 위해 이전 요소를 제거하고 새 요소를 추가하는 범용 함수를 만듭니다.


이 함수를 WijmoSample 컴포넌트 메소드로 사용합니다.


addResource: function (resourceId, resourceLocation, isCulture) {
  // remove previously applied resource
  let element = document.getElementById(resourceId);
  if (element) {
    element.parentNode.removeChild(element);
  }

  // add element
  if (resourceLocation) {
    let element = null;
    const publicPath = process.env.BASE_URL; // publicPath of app (https://cli.vuejs.org/guide/html-and-static-assets.html#the-public-folder)

    if (isCulture) { // script
      element = document.createElement('script');
      element.type = 'text/javascript';
      element.src = publicPath + resourceLocation;<

    } else {  // styleseet
      element = document.createElement('link');
      element.type = 'text/css';
      element.rel = 'stylesheet';
      element.href = publicPath + resourceLocation;
    }
    element.id = resourceId;
    element.onload = () => {
      // refresh all controls on page
      Control.invalidateAll();
    };

    document.head.appendChild(element);
  }
}


웹 서버의 루트가 아닌 폴더에 애플리케이션을 배포 할 경우 "_process.env.BASE_URL"_ 값을 사용합니다. 


이제 " this.addResource" 메소드를 호출하여 리소스를 로드할 수 있습니다 .


// load theme css
this.addResource('theme-element-id', 'public-path-to-theme-css');

// load locale js
this.addResource('js-element-id', 'public-path-to-locale-js', true);


다음에서 테마 및 로케일 리소스의 공용 폴더를 찾습니다.


  • _process.env.WIJMO_THEMES_PUBLIC_FOLDER_
  • _process.env.WIJMO_CULTURES_PUBLIC_FOLDER_ ( "vue.config.js" 파일에서 이전에 정의된 웹팩 구성에 따름)

마지막으로, 테마와 로케일을 선택할 수 있는 두 개의 Wijmo ComboBox 를 추가합니다.


"process.env"변수에서 선택기 항목을 가져옵니다 ( "vue.config.js" 파일 참조 ).


이벤트 핸들러는 테마 및 로케일의 기본값을 각 선택기에 적용합니다.


결과 WijmoSample 코드("src/components/WijmoSample.vue" 파일)는 다음과 같아야 합니다.


<template>
  <div class="wijmo-sample">
    <h1>Wijmo controls sample</h1>

    <hr />
    <h2>Settings</h2>
    <p>
      <strong>Theme:</strong>
      &nbsp;
      <wj-combo-box
        :itemsSource="themes"
        :initialized="themeComboboxInitialized"
        :selectedIndexChanged="themeChanged"
      />
      <br />
      <br />
      <strong>Culture:</strong>
      &nbsp;
      <wj-combo-box
        :itemsSource="cultures"
        :initialized="cultureComboboxInitialized"
        :selectedIndexChanged="cultureChanged"
      />
    </p>
    <hr />

    <p>
      <strong>ComboBox:</strong><br />
      <wj-combo-box :itemsSource="countries" />
    </p>
    <p>
      <strong>InputNumber:</strong><br /><
      <wj-input-number :value="1234.5678" :step="1" />
    </p>
    <p>
      <strong>InputDate:</strong><br />
      <wj-input-date />
    </p>
    <p>
      <strong>Calendar:</strong><br />
      <wj-calendar />
    </p>
    <p>
      <strong>FlexGrid:</strong><br />
      <wj-flex-grid :itemsSource="data">
        <wj-flex-grid-column binding="country" header="Country" />
        <wj-flex-grid-column binding="downloads" header="Downloads" />
        <wj-flex-grid-column binding="sales" header="Sales" format="c0" />
        <wj-flex-grid-column binding="expenses" header="Expenses" format="c0" 
/>
      </wj-flex-grid>
    </p>
  </div>
</template>

<script>
import * as dataSource from '../data';
import "@grapecity/wijmo.styles/wijmo.css";
import "@grapecity/wijmo.vue2.input";
import "@grapecity/wijmo.vue2.grid";
import { Control } from "@grapecity/wijmo";

export default {
  name: 'WijmoSample',
  data: function () {
    return {
      data: dataSource.data,
      countries: dataSource.countries,
      // defined in vue.config.js
      themes: process.env.WIJMO_THEMES,
      cultures: process.env.WIJMO_CULTURES,

      // initial values
      defaultTheme: 'default',
      defaultCulture: 'en',
    };
  },
  methods: {
    themeComboboxInitialized: function (combobox) {
      // apply default theme
      combobox.selectedValue = this.defaultTheme;
      this.themeChanged(combobox);
    },

    themeChanged: function (combobox) {
      // load theme css<
      const themeStyleId = 'wijmo-theme';
      const themeLocation = process.env.WIJMO_THEMES_PUBLIC_FOLDER  // wijmo cultures public path (defined in vue.config.js)
        + '/wijmo.theme.' + combobox.selectedValue + '.css';
      this.addResource(themeStyleId, combobox.selectedIndex && themeLocation);<
    },

    cultureComboboxInitialized: function (combobox) {<
      // apply default culture
      combobox.selectedValue = this.defaultCulture;
      this.cultureChanged(combobox);
    },

    cultureChanged: function (combobox) {
      const scriptCultureId = 'wijmo-culture';
      const cultureLocation = process.env.WIJMO_CULTURES_PUBLIC_FOLDER  // wijmo cultures public path (defined in vue.config.js)
        + '/wijmo.culture.' + combobox.selectedValue + '.js';
      this.addResource(scriptCultureId, cultureLocation, true);
    },

    addResource: function (resourceId, resourceLocation, isCulture) {
      // remove previously applied resource<
      let element = document.getElementById(resourceId);
      if (element) {
        element.parentNode.removeChild(element);
      }

      // add element
      if (resourceLocation) {
        let element = null;
        const publicPath = process.env.BASE_URL; // publicPath of app (https://cli.vuejs.org/guide/html-and-static-assets.html#the-public-folder)

        if (isCulture) { // script
          element = document.createElement('script');
          element.type = 'text/javascript';
          element.src = publicPath + resourceLocation;<
        } else {  // styleseet
          element = document.createElement('link');
          element.type = 'text/css';
          element.rel = 'stylesheet';
          element.href = publicPath + resourceLocation;
        }
        element.id = resourceId;    
        element.onload = () => {
          // refresh all controls on page
          Control.invalidateAll();
        };

        document.head.appendChild(element);
      }
    },
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.wijmo-sample {
  width: 50em;< 
  margin: 3em auto;
}
.wj-calendar {
  width: 25em;
}
</style>


결과 애플리케이션 :



 


애플리케이션 테마 또는 로케일은 해당 선택기 값이 변경될 때마다 변경됩니다.


Vue 프로젝트 작성에 대해 자세히 알아보세요. 


라이브 데모

Wijmo 컴포넌트를 기반으로 하는 Vue 애플리케이션의 테마 및 지역화는 간단합니다. 기본 제공 테마 및 로케일을 적용하는 방법에는 정적 및 동적 두 가지가 있습니다.


정적 메소드는 간단하며 필요한 테마와 로케일을 미리 알고 있을 때 적용할 수 있습니다.


동적 방법은 더 복잡하지만 모양과 문화에 따라 서식을 즉시 변경할 수 있는 애플리케이션을 만들 수 있습니다.



  • 페이스북으로 공유
  • 트위터로  공유
  • 링크 복사
  • 카카오톡으로 보내기

댓글목록

등록된 댓글이 없습니다.

메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기

태그1

인기글

더보기
  • 인기 게시물이 없습니다.
메시어스 홈페이지를 통해 제품에 대해서 더 자세히 알아 보세요!
홈페이지 바로가기
이메일 : sales-kor@mescius.com | 전화 : 1670-0583 | 경기도 과천시 과천대로 7길 33, 디테크타워 B동 1107호 메시어스(주) 대표자 : 허경명 | 사업자등록번호 : 123-84-00981 | 통신판매업신고번호 : 2013-경기안양-00331 ⓒ 2024 MESCIUS inc. All rights reserved.